如何在pandas dataframe中drop_duplicates但保持指定值?

tvokkenx  于 2023-03-28  发布在  其他
关注(0)|答案(1)|浏览(117)

enter image description here

date  price_bl  price_ss  price_bs  price_sl
0 2022-03-09 03:00:00   41198.5       NaN       NaN       NaN
0 2022-03-10 01:00:00       NaN       NaN       NaN   40931.0
0 2022-03-10 01:00:00       NaN       NaN   40931.0       NaN
1 2022-03-16 02:00:00   40867.8       NaN       NaN       NaN
0 2022-03-16 02:00:00       NaN   40867.8       NaN       NaN

# after drop_duplicates...

                 date  price_bl  price_ss  price_bs  price_sl
0 2022-03-09 03:00:00   41198.5       NaN       NaN       NaN
0 2022-03-10 01:00:00       NaN       NaN       NaN   40931.0
1 2022-03-16 02:00:00   40867.8       NaN       NaN       NaN
1 2022-03-16 03:00:00       NaN       NaN       NaN   39137.9
1 2022-03-16 08:00:00       NaN   40289.0       NaN       NaN

如你所见,2022-03-10 01:00:00的price_bs有两个值:40931.0和NaN,在drop_duplicates之后,它变成了一个值NaN。但是我希望它保持正常值,而不是NaN值(如果它有一个正常值和一个NaN值)。我应该怎么做(我的意思是不仅对price_bs列,而且对其他3个price_* 列)?

pod7payv

pod7payv1#

您可以尝试通过groupbymaxfirst等聚合函数组合行:

df = df.groupby('date', as_index=False).max()
# or 
df = df.groupby('date', as_index=False).first() # will use first non-null value in the column for group

相关问题