按 id 上的排名透视 Pandas 数据框

JBS*_*BSH 6 python pivot python-3.x pandas

我目前正在尝试通过 'rank' 上的 'id' 来旋转我的 Pandas DataFrame

print(df)

     id  rank  year  
0   key0  1    2011  
1   key0  2    2012  
2   key0  3    2013  
3   key1  1    2014  
4   key1  2    2015  
5   key1  3    2016  
6   key2  1    2017 
7   key2  2    2018 
8   key2  3    2019 
Run Code Online (Sandbox Code Playgroud)

根据 max('rank'),我想创建尽可能多的 'years' 列并根据升序赋予它们值

print(df)

     id  rank1  year1  rank2  year2  rank3   year3  
0   key0   1     2011    2     2012    3      2013
1   key1   1     2014    2     2015    3      2016  
2   key2   1     2017    2     2018    3      2019
Run Code Online (Sandbox Code Playgroud)

我尝试了自己的解决方案(目前正在工作,但我有大约 200 万行并且不是很有效)

df2= df.melt(id_vars=["id", "rank"], value_vars=[elem for elem in df.columns if elem not ['id','rank']])
df2['col_name'] =df2['variable']+ (df2['rang']-1).astype('str')
df2.value.fillna(0, inplace = True)
df2= pd.pivot_table(df2, index=["id"], columns=["col_name"], values="value", aggfunc=max)
Run Code Online (Sandbox Code Playgroud)

我知道这不是最佳解决方案并且会消耗内存,这就是我要求更好的解决方案的原因

提前致谢

jez*_*ael 3

使用DataFrame.sort_valueswith DataFrame.pivot,排序MultiIndexDataFrame.sort_index然后按 s 展f-string平:

df1 = (df.sort_values(['id','rank'])
         .pivot(index="id",columns="rank", values=["year","rank"])
         .sort_index(axis=1, level=1))
df1.columns = [f'{a}{b}' for a, b in df1.columns]
df1 = df1.reset_index()
print (df1)
     id  rank1  year1  rank2  year2  rank3  year3
0  key0      1   2011      2   2012      3   2013
1  key1      1   2014      2   2015      3   2016
2  key2      1   2017      2   2018      3   2019
Run Code Online (Sandbox Code Playgroud)