我不知道如何問這個問題,但我會盡力解釋我的情況。
我有一個包含以下資料的資料集:
| 產品 | 價值 | 值型別 | 年 |
|---|---|---|---|
| 一種 | 21,5 | 價錢 | 21 |
| 一種 | 5 | 體積 | 21 |
| 乙 | 55,3 | 價錢 | 21 |
| 乙 | 10 | 體積 | 21 |
| C | 70,0 | 價錢 | 21 |
| D | 37,5 | 價錢 | 21 |
| D | 7,7 | 體積 | 21 |
我想達到這樣的目標:
| 產品 | 價錢 | 體積 | 年 |
|---|---|---|---|
| 一種 | 21,5 | 5 | 21 |
| 乙 | 55,3 | 10 | 21 |
| C | 70,0 | —— | 21 |
| D | 37,0 | 7,7 | 21 |
我介意 unstack 函式可以解決問題,但我不知道如何解決,因為我沒有取回所有列。
我找到了一個復雜的解決方案,但它不起作用。
container = []
for label, _df in df.groupby(['Year','Product']):
_df.set_index('Value type', inplace = True)
container.append(pd.DataFrame({
"Product": [label[1]],
"Price":[_df.loc['Price', 'Value']],
"Volume": [_df.loc['Volume', 'Value']],
"Year":[label[0]]}))
df_new = pd.concat(container)
此解決方案不起作用,因為產品 C 的 Volume 缺少行。
我怎樣才能達到預期的資料幀?有沒有什么快速的方法來計算這個?
uj5u.com熱心網友回復:
使用pivot:
out = df.pivot(index=['Product', 'year'], columns='Value type', values=['Value']) \
.droplevel(0, axis=1).reset_index().rename_axis(None, axis=1) \
[['Product', 'Price', 'Volume', 'year']]
>>> out
Product Price Volume year
0 A 21.5 5.0 21
1 B 55.3 10.0 21
2 C 70.0 NaN 21
3 D 37.5 7.7 21
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/325900.html
上一篇:聚合值熊貓
