首页 > 解决方案 > 将数据排序到多索引​​数据框中

问题描述

如何将 DataFrame 中的数据排序到对索引和列都使用 MultiIndex 的 DataFrame 中?

例如,从此转换:

     0    1  2     3     4
0  foo  two  A  2.30  0.01
1  foo  one  A  4.12  0.13
2  bar  two  B  9.89  3.66
3  foo  one  A  2.11  9.48
4  bar  two  A  1.07  5.55

对此:

            A           B      
            1     2     1     2
foo one  2.11  9.48   NaN   NaN
    two   2.3  0.01   NaN   NaN
bar one   NaN   NaN   NaN   NaN
    two  1.07  5.55  9.89  3.66

目前我正在迭代每一行df1并更新 中的值df2,但我想要一个比这更有效的方法:

for index, row in df1.iterrows():
    df2.loc[(row[0], row[1]), row[2]] = list(row[3:])

标签: pythonpandas

解决方案


您可以使用:

def f(x):
    return pd.DataFrame({'a':x.values.ravel()}).rename(lambda x: x + 1)

df = df.groupby([0,1,2])[3,4].apply(f)['a'].unstack([2,3]).sort_index(level=0, axis=1)
df = df.rename_axis((None, None),axis=1).reindex(pd.MultiIndex.from_product(df.index.levels))
print (df)
            A                       B      
            1     2     3     4     1     2
bar one   NaN   NaN   NaN   NaN   NaN   NaN
    two  1.07  5.55   NaN   NaN  9.89  3.66
foo one  4.12  0.13  2.11  9.48   NaN   NaN
    two  2.30  0.01   NaN   NaN   NaN   NaN

说明

  1. 对于前 3 列apply自定义函数的每个组DataFrame,还增加索引值以从1

  2. 重塑并按列unstack排序Multiindexsort_index

  3. 删除列名(2在左角)并将缺少的类别添加到MultiIndex索引reindexMultiIndex.from_product


推荐阅读