python pandas:使用 sort_values 和 drop_duplicates 重复行

问题描述 投票:0回答:2

我有这个数据框

stage
栏中我有4个值:

我在此数据框中有重复的行,我想删除它们,例如:

我想保留#8015行

并且我没有 2 行具有相同的

stage
和相同的
tweet_id
,例如:

我尝试了这个解决方案:

twitter_archive = twitter_rchive.sort_values(by='stage', ascending=False).drop_duplicates(subset='tweet_id', keep='first').sort_index().reset_index(drop=True)

我在这个解决方案中找到了它,但后来我失去了10个

doggo
,尽管我对我的值进行了排序并保留了第一次出现。

python pandas dataframe nan drop-duplicates
2个回答
0
投票

这是您要找的东西吗?

df = pd.DataFrame([{'tweet_id':89324938479283648628, 'name':'Phineas', 'stage': np.nan}, 
                   {'tweet_id':8932493847987465848628, 'name':'Tilly', 'stage': np.nan}, 
                  {'tweet_id':8932493847987465848628, 'name':'Tilly', 'stage': 'Doggo'}])
df = df.groupby(['tweet_id','name']).agg(tuple).applymap(list).reset_index()
df['stage'] = df['stage'].apply(lambda x : [i for i in x if str(i) != 'nan'])
df['stage'] = df['stage'].apply(lambda x : np.nan if len(x) == 0 else x[0])
df

0
投票

首先,您的行中有一个拼写错误: twitter_archive = twitter_rchive.sort_values( #<-- you missing a in archive.sort ...

其次,如果你想保留 stage 的值,请使用 .isnull() 删除 stage = NaN twitter_arc2 = twitter_archive.loc[twitter_archive['stage'].isnull()]

希望这有帮助

© www.soinside.com 2019 - 2024. All rights reserved.