汇总 pandas 数据框中多行的数据
Summarise data over several rows in pandas data frame
我有一个采用这种形式的数据框:
import pandas as pd
dict = {'id':["1001", "1001", "1001", "1002", "1002", "1002", "1003", "1003", "1003"],
'food': ["apple", "ham", "egg", "apple", "pear", "cherry", "cheese", "milk", "cereal"],
'fruit':[1, 0, 0, 1, 1, 1, 0, 0, 0],
'score':[1, 3, 1, 1, 1, 1, 2, 2, 3]}
df = pd.DataFrame(dict)
id food fruit score
0 1001 apple 1 1
1 1001 ham 0 0
2 1001 egg 0 0
3 1002 apple 1 1
4 1002 pear 1 2
5 1002 cherry 1 3
6 1003 cheese 0 0
7 1003 cherry 1 3
8 1003 cheese 0 0
我想创建一个新的数据框,其中一行用于单个参与者(即相同的 ID),然后是用于自定义数据摘要的列,例如:
- 独特食物的数量
- 水果总数
- 总分
- 等等
示例输出:
id unique fruits score
0 1001 3 1 1
1 1002 3 3 6
2 1003 2 1 3
我可以创建一个新的空数据框,然后遍历旧数据框中的唯一 ID,使用逻辑索引来填充列。但是我的数据框有大约 50x10^6 行和大约 200,000 个唯一 ID,所以这会花费很长时间。我读到迭代数据框的行效率低下,但我不知道如何将替代解决方案应用于我的数据集。
谢谢。
groupby().agg()
怎么样:
df.groupby('id', as_index=False).agg({'food':'nunique',
'fruit':'sum',
'score':'sum'})
输出:
id food fruit score
0 1001 3 1 1
1 1002 3 3 6
2 1003 2 1 3
因为 pandas >= 0.25.0
我们有 named aggregations
为此,我们可以聚合并同时为我们的列提供一个更具信息性的名称,因为我们聚合:
所以在这个例子中我们可以一次性创建列unique
。
df.groupby('id').agg(
unique=('food', 'nunique'),
fruits=('fruit', 'sum'),
score=('score', 'sum')
).reset_index()
id unique fruits score
0 1001 3 1 1
1 1002 3 3 6
2 1003 2 1 3
我有一个采用这种形式的数据框:
import pandas as pd
dict = {'id':["1001", "1001", "1001", "1002", "1002", "1002", "1003", "1003", "1003"],
'food': ["apple", "ham", "egg", "apple", "pear", "cherry", "cheese", "milk", "cereal"],
'fruit':[1, 0, 0, 1, 1, 1, 0, 0, 0],
'score':[1, 3, 1, 1, 1, 1, 2, 2, 3]}
df = pd.DataFrame(dict)
id food fruit score
0 1001 apple 1 1
1 1001 ham 0 0
2 1001 egg 0 0
3 1002 apple 1 1
4 1002 pear 1 2
5 1002 cherry 1 3
6 1003 cheese 0 0
7 1003 cherry 1 3
8 1003 cheese 0 0
我想创建一个新的数据框,其中一行用于单个参与者(即相同的 ID),然后是用于自定义数据摘要的列,例如:
- 独特食物的数量
- 水果总数
- 总分
- 等等
示例输出:
id unique fruits score
0 1001 3 1 1
1 1002 3 3 6
2 1003 2 1 3
我可以创建一个新的空数据框,然后遍历旧数据框中的唯一 ID,使用逻辑索引来填充列。但是我的数据框有大约 50x10^6 行和大约 200,000 个唯一 ID,所以这会花费很长时间。我读到迭代数据框的行效率低下,但我不知道如何将替代解决方案应用于我的数据集。
谢谢。
groupby().agg()
怎么样:
df.groupby('id', as_index=False).agg({'food':'nunique',
'fruit':'sum',
'score':'sum'})
输出:
id food fruit score
0 1001 3 1 1
1 1002 3 3 6
2 1003 2 1 3
因为 pandas >= 0.25.0
我们有 named aggregations
为此,我们可以聚合并同时为我们的列提供一个更具信息性的名称,因为我们聚合:
所以在这个例子中我们可以一次性创建列unique
。
df.groupby('id').agg(
unique=('food', 'nunique'),
fruits=('fruit', 'sum'),
score=('score', 'sum')
).reset_index()
id unique fruits score
0 1001 3 1 1
1 1002 3 3 6
2 1003 2 1 3