我有一個以季節為列的資料框。每個季節有兩個品種。我想用一個 item 計算所有專案的每個季節性能A,其中專案A性能將被標記為 100%。
代碼:
xdf = pd.DataFrame({'Season':[1,1,2,2,3,3],'item':['A','B','A','B','A','B'],'value':[25,30,50,75,40,60]})
xdf =
Season item value
0 1 A 25
1 1 B 30
2 2 A 50
3 2 B 75
4 3 A 40
5 3 B 60
預期答案:
xdf =
Season item value %value
0 1 A 25 100
1 1 B 30 120
2 2 A 50 100
3 2 B 75 150
4 3 A 40 100
5 3 B 60 150
uj5u.com熱心網友回復:
Season讓我們在and上創建多索引item以簡化計算:
s = xdf.set_index(['Season', 'item'])['value']
xdf['%value'] = s.div(s.xs('A', level=1)).mul(100).tolist()
Season item value %value
0 1 A 25 100.0
1 1 B 30 120.0
2 2 A 50 100.0
3 2 B 75 150.0
4 3 A 40 100.0
5 3 B 60 150.0
uj5u.com熱心網友回復:
如果您的行順序正確(“A”在“B”之前),您可以使用pct_change. 如果需要先按專案排序。
xdf['%value'] = xdf.groupby('Season')['value'].pct_change().fillna(0) * 100 100
print(xdf)
# Output
Season item value %value
0 1 A 25 100.0
1 1 B 30 120.0
2 2 A 50 100.0
3 2 B 75 150.0
4 3 A 40 100.0
5 3 B 60 150.0
uj5u.com熱心網友回復:
希望這個功能可以解決您的問題。
df=xdf.copy()
for i in xdf['Season'].unique():
_df = xdf[xdf['Season'] == i]
idx = _df.iloc[1:].index
val=_df.iloc[0].value
for j in idx:
cv=xdf.iloc[j].value
xdf.at[j, 'value'] = (100/val)*cv
xdf.loc[xdf.groupby('Season')['value'].head(1).index, 'value'] = 100
df['%value']=xdf['value']
df
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/453897.html
