![](/img/trans.png)
[英]pandas groupby and select value from aother column for ecah group for plotting
[英]update pandas groupby group with column value
我有一個這樣的測試 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 添加到組中的所有行?
我相信您需要對具有與由聚合值填充的原始 DataFrame 相同大小的系列進行transform
:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.