[英]Summarize parts of columns in Pandas dataframe
Let's say I have two columns in my Pandas dataframe 假设我的Pandas数据框中有两列
Category Price
Weekend 30
Weekend 20
Thursday 10
Wednesday 5
Weekend 55
I want to summarize the categories and add the values. 我想总结一下类别并添加值。 I want to add all values of "Weekend"
together and store it in a dictionary for example. 我想将"Weekend"
所有值一起添加并存储在字典中。 So I have something like: 所以我有类似的东西:
summary = {"Weekend":105, "Thursday": 10, "Wednesday": 5}
How can I easily do this? 我怎么能轻松做到这一点?
You could use .groupby()
and then .sum()
. 您可以使用.groupby()
然后使用.sum()
。
>>> df = pd.DataFrame(dict(Category=['Weekend', 'Weekend',
'Thursday', 'Wednesday', 'Weekend'],
Price=[30, 20, 10, 5, 55]))
>>> df.groupby('Category').sum()
Price
Category
Thursday 10
Wednesday 5
Weekend 105
>>> df.groupby('Category').sum().Price.to_dict()
{'Thursday': 10, 'Wednesday': 5, 'Weekend': 105}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.