繁体   English   中英

如何在特定条件下将某个 function 应用于 DataFrame 列值

[英]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)

但我遇到了问题

您可以使用.where()如下:

df['Value'] = df['Value'].where(df['Value'] == -111, np.radians(df['Value']))

.where()如果测试条件为真,则保留系列的值,如果测试条件为假,则替换为第二个参数的值。 因此,它仅在此处的值不等于 -111 时才替换这些值。

结果:

print(df)


   ID       Value
0   1    0.785398
1   2 -111.000000

您可以使用布尔索引:

# 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM