【问题标题】:pandas copy value from one column to another if condition is met如果满足条件,熊猫将值从一列复制到另一列
【发布时间】:2020-06-01 12:00:12
【问题描述】:

我有一个数据框:

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['col1'].mask(df['col1'] < 2,df['col3']),或df = df.assign(col1=df['col1'].mask(df['col1'] < 2,df['col3'])) 或类似np.where

标签: python pandas data-science data-munging


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      你可以看看使用 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 of 2。Eric Yang 的回答将解决您的问题。

      【讨论】:

        【解决方案4】:
        df.loc[df["col1"] < 2, "col1"] = df["col3"]
        

        【讨论】:

          【解决方案5】:
          df['col1'] = df.apply(lambda x: x['col3'] if x['col1'] < x['col2'] else x['col1'], axis=1)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-05-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-12-16
            相关资源
            最近更新 更多