gpt4 book ai didi

python - 根据级别 0 索引对多索引 Pandas DataFrame 的级别 1 索引进行自定义排序

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:23 24 4
gpt4 key购买 nike

我有一个多索引数据帧,df:

arrays = [['bar', 'bar', 'baz', 'baz', 'baz', 'baz', 'foo', 'foo'],
['one', 'two', 'one', 'two', 'three', 'four', 'one', 'two']]

df = pd.DataFrame(np.ones([8, 4]), index=arrays)

看起来像:

             0    1    2    3
bar one 1.0 1.0 1.0 1.0
two 1.0 1.0 1.0 1.0
baz one 1.0 1.0 1.0 1.0
two 1.0 1.0 1.0 1.0
three 1.0 1.0 1.0 1.0
four 1.0 1.0 1.0 1.0
foo one 1.0 1.0 1.0 1.0
two 1.0 1.0 1.0 1.0

我现在需要将 'baz' 子关卡排序为新的顺序,以创建类似于 df_end 的内容:

arrays_end = [['bar', 'bar', 'baz', 'baz', 'baz', 'baz', 'foo', 'foo'],
['one', 'two', 'two', 'four', 'three', 'one', 'one', 'two']]

df_end = pd.DataFrame(np.ones([8, 4]), index=arrays_end)

看起来像:

             0    1    2    3
bar one 1.0 1.0 1.0 1.0
two 1.0 1.0 1.0 1.0
baz two 1.0 1.0 1.0 1.0
four 1.0 1.0 1.0 1.0
three 1.0 1.0 1.0 1.0
one 1.0 1.0 1.0 1.0
foo one 1.0 1.0 1.0 1.0
two 1.0 1.0 1.0 1.0

我认为我可以重新索引 baz 行:

new_index = ['two','four','three','one']

df.loc['baz'].reindex(new_index)

这给出了:

         0    1    2    3
two 1.0 1.0 1.0 1.0
four 1.0 1.0 1.0 1.0
three 1.0 1.0 1.0 1.0
one 1.0 1.0 1.0 1.0

...并将这些值插入到原始 DataFrame 中:

df.loc['baz'] = df.loc['baz'].reindex(new_index)

但结果是:

             0    1    2    3
bar one 1.0 1.0 1.0 1.0
two 1.0 1.0 1.0 1.0
baz one NaN NaN NaN NaN
two NaN NaN NaN NaN
three NaN NaN NaN NaN
four NaN NaN NaN NaN
foo one 1.0 1.0 1.0 1.0
two 1.0 1.0 1.0 1.0

这不是我想要的!所以我的问题是如何使用 new_index 重新排序 baz 索引中的行。任何建议将不胜感激。

最佳答案

编辑:(以适应所需的布局)

arrays = [['bar', 'bar', 'baz', 'baz', 'baz', 'baz', 'foo', 'foo'],
['one', 'two', 'one', 'two', 'three', 'four', 'one', 'two']]

df = pd.DataFrame(np.arange(32).reshape([8, 4]), index=arrays)
new_baz_index = [('baz', i) for i in ['two','four','three','one']]
index = df.index.values.copy()
index[df.index.get_loc('baz')] = new_baz_index
df.reindex(index)

df.index.get_loc('baz') 将获取 baz 部分的位置作为切片对象,我们只替换那里的部分。

enter image description here

关于python - 根据级别 0 索引对多索引 Pandas DataFrame 的级别 1 索引进行自定义排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com