我有几个要添加的数据框。它们的索引范围是0到25,步长为0.5。现在,当我尝试添加索引时,对索引的解释有所不同,新添加的数据框的索引从“ 0到2”的顺序为0.5、1、1.5、10、10.5 ... 19.5、2 ...等。因此,我想列出的10低于2,因为它以1开头,并且数据帧按第一个值对索引进行排序。
我尝试了不同的添加框架的方法:
pd.concat([df1, df2, df3...], axis=0)
df1 + df2 + df3
df1.add(df2, fill_value=0).add(df3.....)
他们都工作。唯一的问题是新的索引弄乱了我的框架。
我当然可以在添加帧之前重置索引,然后再将索引更改回去。但是还有更直接的方法吗?
回答评论:
Index(['0.5', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5', '4.0', '4.5', '5.0',
'5.5', '6.0', '6.5', '7.0', '7.5', '8.0', '8.5', '9.0', '9.5', '10.0',
'10.5', '11.0', '11.5', '12.0', '12.5', '13.0', '13.5', '14.0', '14.5',
'15.0', '15.5', '16.0', '16.5', '17.0', '17.5', '18.0', '18.5', '19.0',
'19.5', '20.0', '20.5', '21.0', '21.5', '22.0', '22.5', '23.0', '23.5',
'24.0', '24.5', '25.0', '25.5', '26.0', '26.5', '27.0', '27.5', '28.0',
'28.5'],
dtype='object') Index(['0.5', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5', '4.0', '4.5', '5.0',
'5.5', '6.0', '6.5', '7.0', '7.5', '8.0', '8.5', '9.0', '9.5', '10.0',
'10.5', '11.0', '11.5', '12.0', '12.5', '13.0', '13.5'],
dtype='object') Index(['0.5', '1.0', '1.5', '2.0', '2.5', '3.0', '3.5', '4.0', '4.5', '5.0',
'5.5', '6.0', '6.5', '7.0', '7.5', '8.0', '8.5', '9.0', '9.5', '10.0',
'10.5', '11.0', '11.5', '12.0', '12.5', '13.0', '13.5', '14.0', '14.5',
'15.0', '15.5', '16.0', '16.5', '17.0', '17.5', '18.0'],
dtype='object')
答案 0 :(得分:1)
一种最简单的解决方案是在所有DataFrame中将索引转换为FloatIndex
:
df1.index = df1.index.astype(float)
df2.index = df2.index.astype(float)
df3.index = df3.index.astype(float)