【问题标题】:Replace specific row-wise duplicate cells in selected columns without dropping rows替换选定列中特定的逐行重复单元格而不删除行
【发布时间】:2020-03-06 13:06:19
【问题描述】:

如何在不删除行的情况下替换选定列中特定的逐行重复单元格(最好不要遍历行)?

基本上,我想保留第一个值并将剩余的重复值替换为 NAN。

例如:

df_example = pd.DataFrame({'A':['a' , 'b', 'c'], 'B':['a', 'f', 'c'],'C':[1,2,3]})
df_example.head() 

原文:

    A   B   C
0   a   a   1
1   b   f   2
2   c   c   3

预期输出:

    A   B   C
0   a   nan 1
1   b   f   2
2   c   nan 3

稍微复杂一点的例子如下:

原文:

    A   B   C D 
0   a   1   a 1
1   b   2   f 5
2   c   3   c 3

预期输出:

    A   B   C D 
0   a   1   nan nan
1   b   2   f 5
2   c   3   nan nan

【问题讨论】:

    标签: python pandas pandas-1.0


    【解决方案1】:

    DataFrame.apply 中的每行使用DataFrame.maskSeries.duplicated

    df_example = df_example.mask(df_example.apply(lambda x: x.duplicated(), axis=1))
    print (df_example)
       A    B  C
    0  a  NaN  1
    1  b    f  2
    2  c  NaN  3
    

    有了新数据:

    df_example = df_example.mask(df_example.apply(lambda x: x.duplicated(), axis=1))
    print (df_example)
       A  B    C    D
    0  a  1  NaN  NaN
    1  b  2    f  5.0
    2  c  3  NaN  NaN
    

    【讨论】:

      猜你喜欢
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 2016-03-17
      • 2021-04-01
      • 1970-01-01
      • 2021-07-01
      相关资源
      最近更新 更多