Python 如何在熊猫中平展groupby操作的结果?
使用Pandas数据帧,有没有一种方法可以在不使用临时数据帧的情况下展平groupby操作的结果,然后将其合并到原始数据帧 假设我需要创建一个“result”列,它依赖于聚合操作,如以下场景:Python 如何在熊猫中平展groupby操作的结果?,python,pandas,Python,Pandas,使用Pandas数据帧,有没有一种方法可以在不使用临时数据帧的情况下展平groupby操作的结果,然后将其合并到原始数据帧 假设我需要创建一个“result”列,它依赖于聚合操作,如以下场景: import pandas as pd df = pd.DataFrame({'box': [1,1,1,2,2,3,3,3,3], 'item': ['apple', 'durian', 'pear', 'orange', 'banana', 'apple', 'pear', 'durian', 'o
import pandas as pd
df = pd.DataFrame({'box': [1,1,1,2,2,3,3,3,3], 'item': ['apple', 'durian', 'pear', 'orange', 'banana', 'apple', 'pear', 'durian', 'orange']})
df['subindex'] = df.groupby('box').cumcount()+1
tmp_df = df.groupby('box')['subindex'].apply(lambda x: (1/x**2).sum()).reset_index(name='result')
df = pd.merge(df, tmp_df, how='inner', on='box')
有没有一种方法可以只在一行代码中的最后两行实现相同的功能,而不必合并两个不同的数据帧?我们可以将两个步骤合并为一个步骤
df['result']=(df.groupby('box').cumcount()+1).groupby(df['box']).\
transform(lambda x : (1/x**2).sum())
0 1.361111
1 1.361111
2 1.361111
3 1.250000
4 1.250000
5 1.423611
6 1.423611
7 1.423611
8 1.423611
dtype: float64
正如@YOBEN_S所指出的,您可以将其组合到一个语句中,然而,您要寻找的关键是
transform
import pandas as pd
df = pd.DataFrame({'box': [1,1,1,2,2,3,3,3,3], 'item': ['apple', 'durian', 'pear', 'orange', 'banana', 'apple', 'pear', 'durian', 'orange']})
df['subindex'] = df.groupby('box').cumcount()+1
df['result'] = df.groupby('box')['subindex'].transform(lambda x: (1/x**2).sum())
print(df)
输出:
box item subindex result
0 1 apple 1 1.361111
1 1 durian 2 1.361111
2 1 pear 3 1.361111
3 2 orange 1 1.250000
4 2 banana 2 1.250000
5 3 apple 1 1.423611
6 3 pear 2 1.423611
7 3 durian 3 1.423611
8 3 orange 4 1.423611
transform
获取一列并将其作为函数应用于该列,并将这些值转换为不同的值,但它保持原始数据帧的相同形状和顺序