我有一个像这样的数据框
A B
1 2
2 -
5 -
4 5
我想在 B 列上应用函数 func()
(但如果传递 -
,该函数会给出错误)。我无法修改 func()
函数。我需要类似的东西:
df['B']=df['B'].apply(func)
仅当值不等于 -
最佳答案
如果满足条件,则使用自定义函数应用于 df 列:
def func(a):
return a + 10
#new pandas dataframe with four rows and 2 columns. 3rd row having a nan
df = pd.DataFrame([[1, 2], [3, 4], [5, pd.np.nan], [7, 8]], columns=["A", "B"])
print(df)
#coerce column named B to numeric
s = pd.to_numeric(df['B'], errors='coerce')
#a mask has true for numeric rows, false for non numeric rows
mask = s.notna()
#mask
print(mask)
#run function named func across the B column
df.loc[mask, 'B'] = s[mask].apply(func)
print(df)
哪些打印:
A B
0 1 2.0
1 3 4.0
2 5 NaN
3 7 8.0
0 True
1 True
2 False
3 True
A B
0 1 12.0
1 3 14.0
2 5 NaN
3 7 18.0
关于python - 如果满足条件,则使用自定义函数应用于 df 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60832597/