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