熊猫:将摘要信息添加到分组框架中的新列中

时间:2018-12-17 00:47:08

标签: python pandas pandas-groupby

从事班级作业。

我们当前的数据集具有如下信息:

    Item ID      Item Name                                  Price
0   108          Extraction, Quickblade Of Trembling Hands  3.53
1   143          Frenzied Scimitar                          1.56
2   92           Final Critic                               4.88
3   100          Blindscythe                                3.27
4   131          Fury                                       1.44

我们被要求按两个值分组。

item_df = popcolumns_df.groupby(["Item ID","Item Name"])  

我遇到了问题,试图将groupby函数附加到此数据帧。例如,当我运行count时,count取代了价格。尝试将价格列中的所有数据替换为计数。

item_counts = item_df.count().reset_index() 

输出:

    Item ID     Item Name           Price
0   0           Splinter             4
1   1           Crucifer             3
2   2           Verdict              6
3   3           Phantomlight         6
4   4           Bloodlord's Fetish   5

尝试2的操作相同:

item_counts = item_df.size().reset_index(name="Counts")

我想要的输出是:

     Item ID    Item Name                Price    Count   Revenue
0    108        Extraction, Quickblade   3.53     12      42.36
1    143        Frenzied Scimitar        1.56     3        4.68
2    92         Final Critic             4.88     2        9.76
3    100        Blindscythe              3.27     1        3.27
4    131        Fury                     1.44     5        7.20

我可能只对各组使用总和来获得收入。我已经为此困扰了几个小时,所以任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

如果任意两个等效项目的价格相同,则可以在分组中包含"Price",然后计算group sizes

summary = popcolumns_df \
    .groupby(["Item ID", "Item Name", "Price"]) \
    .size() \
    .rename("Count") \
    .reset_index()

summary['Revenue'] = summary['Count'] * summary['Price']

pd.Series.rename的调用将最终数据框中的列命名为"Count"

答案 1 :(得分:0)

我认为您正在寻找groupby的transform方法。这将返回原始数据级别的汇总指标。

例如,要在原始数据中创建一个新列以用于某些分组的计数:

df['group_level_count'] = df.groupby(['foo', 'bar']).transform('count')  # or 'size' I think, depending whether you want to count NaNs

相关: * How to count number of rows per group (and other statistics) in pandas group by? * https://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation