Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列名为整数时,按列编号索引数据帧_Python_Pandas - Fatal编程技术网

Python 列名为整数时,按列编号索引数据帧

Python 列名为整数时,按列编号索引数据帧,python,pandas,Python,Pandas,我试图只保留数据帧的某些列,当列名是字符串时,它可以正常工作: In [2]: import numpy as np In [3]: import pandas as pd In [4]: a = np.arange(35).reshape(5,7) In [5]: df = pd.DataFrame(a, ['x', 'y', 'u', 'z', 'w'], ['a', 'b', 'c', 'd', 'e', 'f', 'g']) In [6]: df Out[6]: a

我试图只保留数据帧的某些列,当列名是字符串时,它可以正常工作:

In [2]: import numpy as np

In [3]: import pandas as pd

In [4]: a = np.arange(35).reshape(5,7)

In [5]: df = pd.DataFrame(a, ['x', 'y', 'u', 'z', 'w'], ['a', 'b', 'c', 'd', 'e', 'f', 'g'])

In [6]: df
Out[6]: 
    a   b   c   d   e   f   g
x   0   1   2   3   4   5   6
y   7   8   9  10  11  12  13
u  14  15  16  17  18  19  20
z  21  22  23  24  25  26  27
w  28  29  30  31  32  33  34

[5 rows x 7 columns]

In [7]: df[[1,3]] #No problem
Out[7]: 
    b   d
x   1   3
y   8  10
u  15  17
z  22  24
w  29  31
但是,当列名为整数时,我得到一个键错误:

In [8]: df = pd.DataFrame(a, ['x', 'y', 'u', 'z', 'w'], range(10, 17))

In [9]: df
Out[9]: 
   10  11  12  13  14  15  16
x   0   1   2   3   4   5   6
y   7   8   9  10  11  12  13
u  14  15  16  17  18  19  20
z  21  22  23  24  25  26  27
w  28  29  30  31  32  33  34

[5 rows x 7 columns]

In [10]: df[[1,3]]
结果:

KeyError: '[1 3] not in index'

我可以理解为什么熊猫不允许->来避免按列名和列号进行索引的混淆。然而,有没有一种方法可以告诉熊猫,我想按列数进行索引?当然,一个解决方案是将列名转换为字符串,但我想知道是否有更好的解决方案。

这当然是一个感觉像bug但实际上是一个设计决策的问题(我认为)

一些解决方案:

将列的位置作为其名称重命名:

 df.columns = arange(0,len(df.columns))
另一种方法是从
df.columns
获取名称:

print df[ df.columns[[1,3]] ]
   11  13
x   1   3
y   8  10
u  15  17
z  22  24
w  29  31

我认为这是最吸引人的,因为它只需要添加一点点代码,而不需要更改任何列名

这正是iloc的目的,请参见


只需将标题从整数转换为字符串。在使用pandas数据集时,这几乎总是一种最佳做法,以避免意外

df.columns = df.columns.map(str)
df.columns = df.columns.map(str)