繁体   English   中英

如果满足条件,pandas 将值从一列复制到另一列

[英]pandas copy value from one column to another if condition is met

我有一个数据框:

df = 
col1  col2  col3 
1      2     3
1      4     6
3      7     2

我想编辑df ,以便当 col1 的值小于 2 时,从col3获取值。

所以我会得到:

new_df = 
col1  col2  col3 
3      2     3
6      4     6
3      7     2

我尝试使用assigndf.loc但没有用。

这样做的最佳方法是什么?

df['col1'] = df.apply(lambda x: x['col3'] if x['col1'] < x['col2'] else x['col1'], axis=1)

这种最有效的方法是使用loc运算符:

mfilter = df["col1"] < df["col2"]
df.loc[mfilter, "col1"] = df.loc[mfilter, "col3"]
df.loc[df["col1"] < 2, "col1"] = df["col3"]

正如@anky_91 所提到的,使用np.where来更新'col1'值:

df['col1'] = np.where(df['col1'] < df['col2'], df['col3'], df['col1'])

你可以看看使用apply函数。

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html

df['col1'] = df.apply(lambda c: c['col3'] if c['col1'] < 2 else c['col1'], axis=1)

编辑:抱歉,我从您的模拟结果中看到您指的是 col2 而不是 int 2。Eric Yang 的回答将解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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