簡體   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