用列值更新pandas groupby group

神剑

我有这样的测试df:

df = pd.DataFrame({'A': ['Apple','Apple', 'Apple','Orange','Orange','Orange','Pears','Pears'],
                    'B': [1,2,9,6,4,3,2,1]
                   })
       A    B
0   Apple   1
1   Apple   2
2   Apple   9
3   Orange  6
4   Orange  4
5   Orange  3
6   Pears   2
7   Pears   1

现在,我需要在col'B'中添加一个具有相应%differences的新列。这怎么可能。我无法使它正常工作。

我看过pandas groupby()。last()的更新列值,不确定是否与我的问题有关。

而这看起来很有希望,Pandas Groupby和Sum Only One Column

我需要查找并在col maxpercchng(组中的所有行)中插入每组col'A'的col(B)的最大变化。所以我想出了这段代码:

grouppercchng = ((df.groupby['A'].max() - df.groupby['A'].min())/df.groupby['A'].iloc[0])*100

并尝试将其添加到组col'maxpercchng'中,如下所示

group['maxpercchng'] = grouppercchng

或者像这样

df_kpi_hot.groupby(['A'], as_index=False)['maxpercchng'] = grouppercchng

有谁知道如何将maxpercchng col添加到组中的所有行?

耶斯列尔

我相信您需要transform具有与原始DataFrame相同大小的Series,并由汇总值填充:

g = df.groupby('A')['B']
df['maxpercchng'] = (g.transform('max') - g.transform('min')) /  g.transform('first') * 100

print (df)

        A  B  maxpercchng
0   Apple  1        800.0
1   Apple  2        800.0
2   Apple  9        800.0
3  Orange  6         50.0
4  Orange  4         50.0
5  Orange  3         50.0
6   Pears  2         50.0
7   Pears  1         50.0

要么:

g = df.groupby('A')['B']
df1 = ((g.max() - g.min()) / g.first() * 100).reset_index()
print (df1)

        A      B
0   Apple  800.0
1  Orange   50.0
2   Pears   50.0

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章