如何用pandas组织数据帧中的数据

2024-09-26 17:52:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像

     used_at  common users                     pair of websites
0       2014          1364                   avito.ru and e1.ru
1       2014          1364                   e1.ru and avito.ru
2       2014          1716                 avito.ru and drom.ru
3       2014          1716                 drom.ru and avito.ru
4       2014          1602                 avito.ru and auto.ru
5       2014          1602                 auto.ru and avito.ru
6       2014           299           avito.ru and avtomarket.ru
7       2014           299           avtomarket.ru and avito.ru
8       2014           579                   avito.ru and am.ru
9       2014           579                   am.ru and avito.ru

20142015年中,所有字符串都是重复的。我需要打印我的数据

^{pr2}$

我想删除重复的字符串,而是将每对打印到第一个输出2014,然后输出2015。 我试着这么做:

all_common_users = df.groupby([df['used_at'].dt.year]).apply(f).reset_index(drop=True, level=1).reset_index()

common_users = all_common_users.groupby(all_common_users.index / 2).first().sort_values('pair of websites')


# keep only 'interesting' columns
common_users = common_users[['pair of websites','used_at','common users']]
common_users.columns = ['pair of websites','year','common users']

df = common_users[common_users.groupby('pair of websites')['common users']].sort_values('pair of websites', ascending=False).reset_index()

但打印错误。我做错什么了?在


Tags: andofdfindexrucommonallusers
1条回答
网友
1楼 · 发布于 2024-09-26 17:52:02

您可以使用pandas.DataFrame.drop_duplicates

df.drop_duplicates(subset=["used_at", "common users"])
   used_at  common users            pair of websites
0     2014          1364          avito.ru and e1.ru
2     2014          1716        avito.ru and drom.ru
4     2014          1602        avito.ru and auto.ru
6     2014           299  avito.ru and avtomarket.ru
8     2014           579          avito.ru and am.ru

使用subset

column label or sequence of labels, optional Only consider certain columns for identifying duplicates, by default use all of the columns

相关问题 更多 >

    热门问题