gpt4 book ai didi

python - pandas 在层次索引级别上匹配

转载 作者:行者123 更新时间:2023-12-01 05:08:57 24 4
gpt4 key购买 nike

我正在尝试制作摘要 DataFrame,但他们的填写方式会导致问题,因为没有对标签进行检查。

这是一个玩具示例:

import numpy as np
import pandas as pd

arrays = [np.hstack([ ['one']*3, ['two']*3]), ['Dog', 'Bird', 'Cat']*2]
columns = pd.MultiIndex.from_arrays(arrays, names=['foo', 'bar'])

df = pd.DataFrame(np.zeros((3,6)),columns=columns,
index=pd.date_range('20000103',periods=3))

df['one'] = pd.DataFrame({'Bird' : np.ones(3)*2,
'Dog' : np.ones(3),
'Cat' : np.ones(3)*3},
index= pd.date_range('20000103',periods=3))
df['two'] = pd.DataFrame({'Dog' : np.ones(3)*4,
'Bird' : np.ones(3)*5,
'Cat' : np.ones(3)*6,},
index= pd.date_range('20000103',periods=3))

输出为:

foo            one          two
bar Dog Bird Cat Dog Bird Cat
2000-01-03 2 3 1 5 6 4
2000-01-04 2 3 1 5 6 4
2000-01-05 2 3 1 5 6 4

我期望的地方:

foo            one          two
bar Dog Bird Cat Dog Bird Cat
2000-01-03 1 2 3 4 5 6
2000-01-04 1 2 3 4 5 6
2000-01-05 1 2 3 4 5 6

问题在于框架是按列的字母顺序排序的。然后将其插入到较大的框架中,并对值进行排序,并且列标签是错误的。

所以我的问题是是否有办法确保列标签匹配?

最佳答案

这应该在各个级别上保持一致(尽管如何如何做到这一点有些模糊,例如在哪个级别上)。 https://github.com/pydata/pandas/issues/7655

你应该这样做:

In [10]: one = pd.DataFrame({'Bird' : np.ones(3)*2,
'Dog' : np.ones(3),
'Cat' : np.ones(3)*3},
index= pd.date_range('20000103',periods=3))

In [11]: two = pd.DataFrame({'Dog' : np.ones(3)*4,
....: 'Bird' : np.ones(3)*5,
....: 'Cat' : np.ones(3)*6,},
....: index= pd.date_range('20000103',periods=3))

In [12]: one
Out[12]:
Bird Cat Dog
2000-01-03 2 3 1
2000-01-04 2 3 1
2000-01-05 2 3 1

In [13]: two
Out[13]:
Bird Cat Dog
2000-01-03 5 6 4
2000-01-04 5 6 4
2000-01-05 5 6 4

In [14]: concat([one,two],keys=['one','two'],axis=1)
Out[14]:
one two
Bird Cat Dog Bird Cat Dog
2000-01-03 2 3 1 5 6 4
2000-01-04 2 3 1 5 6 4
2000-01-05 2 3 1 5 6 4

关于python - pandas 在层次索引级别上匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24553921/

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