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

时间:2020-02-17 14:15:57

标签: python pandas data-science data-munging

我有一个数据框:

Header parameters named Accept, Content-Type and Authorization are not allowed. To describe these headers, use the corresponding OpenAPI keywords

我要编辑df = col1 col2 col3 1 2 3 1 4 6 3 7 2 ,以便当col1的值小于2时,从df中取值。

所以我会得到:

col3

我尝试使用new_df = col1 col2 col3 3 2 3 6 4 6 3 7 2 assign,但是没有用。

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

5 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

如@ anky_91所述,使用np.where更新'col1'值:

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

答案 4 :(得分:0)

您可以使用应用功能查看。

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而不是2的int。EricYang的答案将解决您的问题。

相关问题