3
我要重塑以下數據幀:重塑熊貓數據幀(複雜的情況下!)
index id numbers 1111 5 58.99 2222 5 75.65 1000 4 66.54 11 4 60.33 143 4 62.31 145 51 30.2 1 7 61.28
重整的數據幀應該是這樣的:
id 1 2 3 5 58.99 75.65 nan 4 66.54 60.33 62.31 51 30.2 nan nan 7 61.28 nan nan
我用下面的代碼來做到這一點。
import pandas as pd
dtFrame = pd.read_csv("data.csv")
ids = dtFrame['id'].unique()
temp = dtFrame.groupby(['id'])
temp2 = {}
for i in ids:
temp2[i]= temp.get_group(i).reset_index()['numbers']
dtFrame = pd.DataFrame.from_dict(temp2)
dtFrame = dtFrame.T
雖然上面的代碼解決了我的問題,但有沒有更簡單的方法來實現這一點。我試過Pivot表,但它不能解決問題,也許它需要在每個組中具有相同數量的元素。或者可能有另一種我不知道的方式,請分享你的想法。
謝謝unutbu .. – user1124825