gpt4 book ai didi

python - 当行可以属于多个组时,对 pandas Series 或 DataFrame 的行进行分组

转载 作者:行者123 更新时间:2023-11-30 22:08:44 25 4
gpt4 key购买 nike

Series/DataFrame 对象的项目/行各自属于一个组时,pandas 的 groupby 方法非常有用。但我遇到的情况是,每一行可以属于零个、一个或多个组。

带有一些假设数据的示例:

+--------+-------+----------------------+
| Item | Count | Tags |
+--------+-------+----------------------+
| Apple | 5 | ['fruit', 'red'] |
| Tomato | 10 | ['vegetable', 'red'] |
| Potato | 3 | [] |
| Orange | 20 | ['fruit'] |
+--------+-------+----------------------+

根据标签列,Apple 和 Tomato 均属于两个组,Potato 不属于任何组,而 Orange 属于一组。因此,按标签分组并对每个标签的计数求和应给出:

+-----------+-------+
| Tag | Count |
+-----------+-------+
| fruit | 25 |
| red | 15 |
| vegetable | 10 |
+-----------+-------+

这个操作如何完成?

最佳答案

'Tags' 的长度分解您的 'Count'

df.Count.repeat(df.Tags.str.len()).groupby(np.concatenate(df.Tags)).sum()

fruit 25
red 15
vegetable 10
Name: Count, dtype: int64
<小时/>

numpy.bincountpandas.factorize

i, r = pd.factorize(np.concatenate(df.Tags))
c = np.bincount(i, df.Count.repeat(df.Tags.str.len()))

pd.Series(c.astype(df.Count.dtype), r)

fruit 25
red 15
vegetable 10
dtype: int64
<小时/>

通用解决方案

from collections import defaultdict
import pandas as pd

counts = [5, 10, 3, 20]
tags = [['fruit', 'red'], ['vegetable', 'red'], [], ['fruit']]
d = defaultdict(int)

for c, T in zip(counts, tags):
for t in T:
d[t] += c

print(pd.Series(d))
print()
print(pd.DataFrame([*d.items()], columns=['Tag', 'Count']))

fruit 25
red 15
vegetable 10
dtype: int64

Tag Count
0 fruit 25
1 red 15
2 vegetable 10

关于python - 当行可以属于多个组时,对 pandas Series 或 DataFrame 的行进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52101276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com