【问题标题】:Apply filter on one column and replicate the values in another column for the same filter在一列上应用过滤器并为同一过滤器复制另一列中的值
【发布时间】:2021-09-01 11:15:45
【问题描述】:

当前 Pandas 数据框,包含两列(A、B),如下所示

A 列 = G、H、A、B、D、A、A

B 列 = 苹果、香蕉、桃子、番石榴、橙子、葡萄、草莓

在 A 列,我想首先过滤掉 'A'

接下来我想更新列 B 的相应字段中的“A”,如下所述,保留 B 中的其他值

所需的Pandas 数据框

A 列 = G、H、A、B、D、A、A

B 列 = 苹果、香蕉、A、番石榴、橙子、AA

希望我的问题是清晰和理解的。请求代码方面的帮助。提前致谢

【问题讨论】:

  • import numpy as np;df['Column B'] = np.where(df['Column A'].eq('A') ,df['Column A'], df['Column B']) 条件赋值非常简单,在文档和10 minutes to pandas guide 中很容易找到 - 投票结束。

标签: python pandas dataframe


【解决方案1】:

如果我理解正确的话:

df.loc[df['A']=='A','B']='A'

结果 df:

【讨论】:

    【解决方案2】:

    Pandas.loc 是您需要在 A 列是 A 的位置进行过滤,然后将 B 中的相应值更改为 A。

    df = pd.DataFrame({'A' : ['G', 'H', 'A', 'B', 'D', 'A', 'A'],
                       'B' : ['apple', 'banana', 'peach', 'guava', 'orange', 'grapes', 'strawberry']})
    
    df.loc[df['A'] == 'A', 'B'] = 'A'
    
        print(df)
    
       A       B
    0  G   apple
    1  H  banana
    2  A       A
    3  B   guava
    4  D  orange
    5  A       A
    6  A       A
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-12
      相关资源
      最近更新 更多