我有一个任务,我必须在 Dataframe 中找到一个权重值,它可以在几列中找到(但不是每列)
简化的 Dataframe 如下所示:
str1 str2
0 some string 2kg.
1 got 5kg some string
2 some string some string
它现在如何工作的简化示例:
import re
import pandas as pd
from pandas import Series
regex = re.compile(r'(\d+)kg')
def find_weight(row: Series) -> int | None:
# first check in 'str1'
result = re.search(pattern=regex, string=row['str1'])
if result:
return int(result.group(1))
# if not found, check 'str2'
result = re.search(pattern=regex, string=row['str2'])
if result:
return int(result.group(1))
# if nothing found in both strings - return None
return None
df = pd.DataFrame([['some string', '2kg.'], ['got 5kg', 'some string'], ['some string', 'some string']], columns=['str1', 'str2'])
df['weight'] = df.apply(find_weight, axis=1)
print(df)
然而,在现实生活中,我有40多列,而权重值只能在其中两列中找到,每次传递一整行给函数感觉很浪费,我怎么能只传递几列的参数而不是整行呢?
如何仅将'str1'和'str2'列的值传递给函数,然后将其应用于每一行?
1条答案
按热度按时间qltillow1#
解决方案为:
感谢@HenryEcker!