简体   繁体   中英

update pandas groupby group with column value

I have a test df like this:

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

Now I need to add a new column with the respective %differences in col 'B'. How is this possible. I cannot get this to work.

I have looked at update column value of pandas groupby().last() Not sure that it is pertinent to my problem.

And this which looks promising Pandas Groupby and Sum Only One Column

I need to find and insert into the col maxpercchng (all rows in group) the maximum change in col (B) per group of col 'A'. So I have come up with this code:

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

and try to add it to the group col 'maxpercchng' like so

group['maxpercchng'] = grouppercchng

Or like so

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

Does anyone know how to add to all rows in group the maxpercchng col?

I believe you need transform for Series with same size like original DataFrame filled by aggregated values:

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

Or:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM