简体   繁体   English

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

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

相关问题 如何通过数据框中的名称将功能应用于特定列 - How to apply a function to a certain column by name in a dataframe 为数据框中的两个列值的组合为特定条件添加新列 - Adding a new column for a certain condition for a combination of two column values in dataframe 当给定某个条件时,通过pandas数据帧的列中的用户定义函数输入值 - Input values through a user-defined function in a column of a pandas dataframe when a certain condition is given 如何根据特定条件替换列中的某些值? - How to replace certain values in a column based on a certain condition? 如何根据数据框中的列条件应用函数 - How to apply function on the basis of column condition in a dataframe 如何在列中创建具有某些值的数据框的子集? - How to create a subset of a dataframe with certain values in a column? 如何在给定特定条件下更改 dataframe 列值 - How do I change the dataframe column values given certain condition(s) 根据特定列中的条件应用公式 - Apply formula based on condition in certain column 仅针对另一列的某个值对除某些列之外的所有列应用条件 - Apply a condition on all but certain columns only for a certain value of another column 如何在满足数据框中条件的行中提取某些值? - How do i extract certain values in a row satisfying a condition in a dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM