我有一个熊猫数据框,我通过阅读各种CSV文件构建。它看起来像这样:熊猫.sortlevel不能排序负数
ID V2 H1-b V3 H2 V1 H1a
position -50.0 600.0 -125.0 -720.0 23.0 450.0
2000-01-01 -1.057609 1.160002 1.082879 -1.304001 -0.259283 1.285260
2000-02-01 -1.133474 -0.385869 0.756780 2.311465 1.060337 -1.059041
2000-03-01 1.209086 -0.774133 0.018603 0.969665 -1.221080 1.717816
...
当我试着使用df_sort = df.sortlevel(level=1,axis=1)
(或sortlevel='position'
,相同的结果)排序它,我得到以下结果:
ID V3 V2 H2 V1 H1-a H1-b
position -125.0 -50.0 -720.0 23.0 450.0 600.0
2000-01-01 1.082879 -1.057609 -1.304001 -0.259283 1.285260 1.160002
2000-02-01 0.756780 -1.133474 2.311465 1.060337 -1.059041 -0.385869
2000-03-01 0.018603 1.209086 0.969665 -1.221080 1.717816 -0.774133
正数进行排序的正确方法(23 600),但负数是“随机的”。
据我所知,我所有的CSV文件都是相同的(数字之前没有空格),并且数据框中的所有条目都是由同一个脚本生成的。
但是,当我想看看我是否能重现用一个简单的合成数据帧,整理作品:
header=pd.MultiIndex.from_product([[-3,-300,4,100,34,-324],['s']],names=['loc','X'])
df = pd.DataFrame(np.random.randn(5, 6), index=['a','b','c','d','e'], columns = header)
结果
In [6]: df.head()
Out[6]:
loc -3 -300 4 100 34 -324
S s s s s s s
a -0.444521 -0.616153 2.261075 -1.857406 0.367582 1.212705
b -1.389062 -0.741163 0.512457 1.013495 -2.003147 0.651232
c -0.376925 -0.271408 -0.854247 0.355438 -0.791896 -1.359056
d -2.929450 0.228446 1.287110 -1.117579 -0.501250 1.340859
e -0.653089 0.245901 0.036066 0.776839 -1.112828 -0.476782
In [9]: df_sort = df.sortlevel('loc',axis=1)
In [10]: df_sort.head()
Out[10]:
loc -324 -300 -3 4 34 100
S s s s s s s
a 1.212705 -0.616153 -0.444521 2.261075 0.367582 -1.857406
b 0.651232 -0.741163 -1.389062 0.512457 -2.003147 1.013495
c -1.359056 -0.271408 -0.376925 -0.854247 -0.791896 0.355438
d 1.340859 0.228446 -2.929450 1.287110 -0.501250 -1.117579
e -0.476782 0.245901 -0.653089 0.036066 -1.112828 0.776839
如不sortlevel(level = 0
最初的想法是索引中的其他内容会干扰排序,但df_sort = df_GW.sortlevel(level='location',axis=1,sort_remaining=False)
不会更改排序中的任何内容。
我在做什么错?
我怀疑,无论出于什么原因,某件东西被当作一个字符串或其他东西来对待,但是我找不到任何指示。
EDIT的df.dtypes
输出: 真实DF:
In [29]: df_GW.dtypes
Out[29]:
ID Position
V2 -50.0 float64
H1-b 600.0 float64
V3 -125.0 float64
H2 -720.0 float64
V1 23.0 float64
H1-a 450.0 float64
dtype: object
合成:
AttributeError: 'DataFrame' object has no attribute 'dtype'
df.columns
真实:
MultiIndex(levels=[[u'H1-a', u'H1-b', u'H2', u'V1', u'V2', u'V3'], [u'-125.0', u'-50.0', u'-720.0', u'23.0', u'450.0', u'600.0']],
labels=[[4, 1, 5, 2, 3, 0], [1, 5, 0, 2, 3, 4], [4, 1, 5, 2, 3, 0], [0, 0, 0, 0, 0, 0]], #not sure what's happening here. The original df is a bit bigger, and I'm cutting it to size
names=[u'ID', u'position'])
合成:
MultiIndex(levels=[[-720.0, -125.0, -50.0, 23.0, 450.0, 600.0], [u's']],
labels=[[2, 5, 1, 0, 3, 4], [0, 0, 0, 0, 0, 0]],
names=[u'loc', u'S'])
'df.dtypes'的输出是什么? –
与真实的和合成的数据我得到一个错误“DataFrame”对象没有属性“types”。 –
什么返回'df.columns'? – jezrael