[英]How to apply a certain function to DataFrame column values on a certain condition
我有下面的df:
ID Value
1 45
2 -111
df = pd.DataFrame(columns=['ID', 'Value'], data=[['1', '45'], ['2', '-111'])
当且仅当当前值不等于 -111 时,如何将 np.radians() function 应用于值列?
最终 output 将是:
ID Value
1 0.785398
2 -111
我正在尝试做类似的事情
df['Value'] = df.apply(lambda row: '-111' if row['Value'] == '-111' else np.radians(row['Value'].astype(float)), axis=1)
但我遇到了问题
您可以使用布尔索引:
# convert Value column to float
df["Value"] = df["Value"].astype(float)
# create a mask
mask = df.Value != -111
# apply np.radians using the mask
df.loc[mask, "Value"] = df.loc[mask, "Value"].apply(np.radians)
print(df)
印刷:
ID Value
0 1 0.785398
1 2 -111.000000
np.where
选项:
df.Value = np.where(df.Value.ne(-111), radians(df.Value) , df.Value)
完整代码:
from numpy import radians
df.Value = df.Value.astype(int)
df.Value = np.where(df.Value.ne(-111), radians(df.Value) , df.Value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.