如何使用熊猫对每个分组和计数的记录按组输出单个记录

时间:2019-01-29 08:08:42

标签: python pandas

我正在使用Pandas处理数据文件,并尝试以分组形式输出数据,这非常类似于SQL分组功能,每组只有一条唯一记录

我有一个数据文件,其中包含一些假游戏的统计信息。我试图按游戏的发布年份对游戏进行分组,并按照年份和该年的游戏数量在每组中显示1条记录。 到目前为止,我可以算出游戏数,但输出包含按以下方式计数的所有记录:

import pandas as pd

print("*** All data count ***")
data = pd.read_csv('../input/games.csv')
print(len(data))

print("*** No duplicates ***")
no_dups = data.drop_duplicates()
print(len(no_dups))

print("*** drop unused columns: type and name for better ")
no_shit = no_dups.drop(['type', 'name', ], axis=1)

print("*** Invalid removed")
cols = ['yearpublished']
no_shit[cols] = no_shit[no_shit[cols] > 0][cols]
clean_data = no_shit.dropna()
print(len(clean_data))

print("*** Valid sorted ***")
sorted_data = clean_data.sort_values(cols)
sorted_data['title_count'] = sorted_data.groupby('yearpublished')['id'].cumcount() + 1

print(sorted_data.tail(20))

现在的输出如下所示,因此我的代码实际上是对记录进行分组,但显示所有记录而不是最后一个记录。

>            id  yearpublished     ...       average_weight  title_count 78848  177659         2016.0     ...               4.0000          296
> 81003  183415         2016.0     ...               0.0000          297
> 79401  179448         2016.0     ...               0.0000          298
> 81107  183684         2017.0     ...               0.0000            1
> 79706  180185         2017.0     ...               0.0000            2
> 80431  181888         2017.0     ...               0.0000            3
> 80676  182408         2017.0     ...               0.0000            4
> 62324  127709         2017.0     ...               2.6667            5
> 76115  170599         2017.0     ...               2.0000            6
> 77249  173635         2017.0     ...               0.0000            7
> 80039  181006         2017.0     ...               0.0000            8
> 65192  135986         2017.0     ...               4.0000            9
> 79263  178958         2017.0     ...               0.0000           10
> 64446  133601         2017.0     ...               0.0000           11
> 64447  133602         2017.0     ...               0.0000           12
> 81247  184151         2017.0     ...               0.0000           13
> 80677  182409         2017.0     ...               0.0000           14
> 79942  180797         2018.0     ...               0.0000            1
> 81294  184349         2018.0     ...               0.0000            2
> 80092  181140         2018.0     ...               0.0000            3

我想要此输出instad:

 id  yearpublished     ...       average_weight  title_count
79401  179448         2016.0     ...               0.0000          298
80677  182409         2017.0     ...               0.0000           14
80092  181140         2018.0     ...               0.0000            3

0 个答案:

没有答案