繁体   English   中英

如何删除特定条件的值并替换它们?

[英]How do I drop values of a specific condition and replace those?

我的 dataframe 看起来像这样:

ID 第一的 第二 第四 第五
1
2
3
4
5

代码:

df = {'ID': [1, 2, 3, 4, 5],
        'first': ['one', 'one', 'one', 'one', 'one']
'second': ['one', 'two', 'three','one','one']
'fourth': ['two', 'two', 'three','one','two']
'fifth': ['three','three','three','one', 'one']
        }

我也想在一行中删除/删除出现在下一列(右)中的那些值。 所以有很多重复,但是如果在一个相同的值之间有另一个值,比如“ID”5,那么应该只删除第二列的值,这样 df 最终看起来像这样:

ID 第一的 第二 第四 第五
1
2
3
4
5

您可以使用每行的drop_duplicates并重新索引:

out = (df
 .set_index('ID')
 .apply(lambda s: (s2:=s.drop_duplicates())
                  .set_axis(s.index[:len(s2)]),
        axis=1)
 .reset_index().reindex(df.columns, axis=1)
)

output:

   ID first second fourth  fifth
0   1   one    Two  Three    NaN
1   2   one    Two  Three    NaN
2   3   one  Three    NaN    NaN
3   4   one    NaN    NaN    NaN
4   5   one    two    NaN    NaN

你可以做shift然后使用 NaN 替换相同

out = df.where(lambda x : df.ne(df.shift(1,axis=1))).transform(lambda x: sorted(x, key=pd.isnull),1)
Out[73]: 
  ID first second fourth fifth
0  1   one    Two  Three   NaN
1  2   one    Two  Three   NaN
2  3   one  Three    NaN   NaN
3  4   one    NaN    NaN   NaN
4  5   one    two    one   NaN

暂无
暂无

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

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