【发布时间】:2019-12-04 22:55:17
【问题描述】:
我有 3 列,我想根据这 3 列中的常用值进行计数,例如
Dataframe is
Date Name SoldItem
15-Jul Joe TV
15-Jul Joe Fridge
15-Jul Joe Washing Machine
15-Jul Joe TV
15-Jul Joe Fridge
15-Jul Mary Chair
15-Jul Mary Fridge
16-Jul Joe Fridge
16-Jul Joe Fridge
16-Jul Tim Washing Machine
17-Jul Joe Washing Machine
17-Jul Jimmy Washing Machine
17-Jul Joe Washing Machine
17-Jul Joe Washing Machine
And final output should be
Date Name SoldItem Count
15-Jul Joe TV 2
Joe Fridge 2
Joe Washing Machine 1
Mary Chair 1
Mary Fridge 1
16-Jul Joe Fridge 2
Tim Washing Machine 1
17-Jul Joe Washing Machine 3
Jimmy Washing Machine 1
我尝试了下面的代码,但它只适用于 2 列
df.groupby(["Date", "Name"]).size()
provides like
Date Name
15-Jul Joe 5
Mary 2
16-Jul Joe 2
Tim 1
17-Jul Joe 3
Jimmy 1
When i use the below
df.groupby(["Date", "Name", "SoldItem"]).size()
it throws the error
ValueError: Length of passed values is xx, index implies 0
这就是我加载数据帧的方式
fields = ['Date', 'Name', 'SoldItem']
df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
df_grp = df.groupby(["Date", "Name"]).size()
print df_grp
如果您能建议我如何根据 3 个值进行分组并提供计数,我将不胜感激。非常感谢提前。我也是 Python 新手。
【问题讨论】:
-
你的数据集中有缺失值吗?
标签: python dataframe group-by count