[英]How to apply a certain function to DataFrame column values on a certain condition
I have the df below:我有下面的df:
ID Value
1 45
2 -111
df = pd.DataFrame(columns=['ID', 'Value'], data=[['1', '45'], ['2', '-111'])
How can I apply the np.radians() function to the Value column if and only if the current value does not equal -111?当且仅当当前值不等于 -111 时,如何将 np.radians() function 应用于值列?
Final output would be:最终 output 将是:
ID Value
1 0.785398
2 -111
I am trying to do something like我正在尝试做类似的事情
df['Value'] = df.apply(lambda row: '-111' if row['Value'] == '-111' else np.radians(row['Value'].astype(float)), axis=1)
but am running into isssues但我遇到了问题
You can use .where()
as follows:您可以使用
.where()
如下:
df['Value'] = df['Value'].where(df['Value'] == -111, np.radians(df['Value']))
.where()
keeps the values of the series if the test condition is true and replace by the values of the second parameter if the test condition is false. .where()
如果测试条件为真,则保留系列的值,如果测试条件为假,则替换为第二个参数的值。 Thus, it replace the values only when the value not equals -111 here.因此,它仅在此处的值不等于 -111 时才替换这些值。
Result:结果:
print(df)
ID Value
0 1 0.785398
1 2 -111.000000
You can use boolean-indexing:您可以使用布尔索引:
# 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)
Prints:印刷:
ID Value
0 1 0.785398
1 2 -111.000000
np.where
option: np.where
选项:
df.Value = np.where(df.Value.ne(-111), radians(df.Value) , df.Value)
Full code:完整代码:
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.