pandas 按索引(列)编号选择熊猫数据框中的列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53095216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:07:21  来源:igfitidea点击:

Select columns in pandas dataframe by index (column) number

pythonrpandasdataframe

提问by Mario Reyes

I have been mainly an R user up until now, and I am now trying to get better with Python, so please keep that in mind as I may not be thinking in a pythonic way...

到目前为止,我主要是一个 R 用户,我现在正在尝试使用 Python 变得更好,所以请记住这一点,因为我可能不会以 Pythonic 的方式思考......

In any case, here it goes, I want to subset a pandas dataframe by column position, where I would select for instance, the first 2 columns, the the 4th column, and then the last two columns.

无论如何,在这里,我想按列位置对 Pandas 数据框进行子集化,例如,我将在其中选择前 2 列、第 4 列和最后两列。

The code I used for that is as follows:

我为此使用的代码如下:

df01 = pd.DataFrame(np.random.randint(low=0, high=10, size=(10, 10)),
                columns=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i','j'])
df01.iloc[:,list(range(0,2)) + list([3]) + list(range(-3,-1))]

I am doing the subsetting by essentially creating 3 lists with the columns I want, but I am thinking there must be a better way to do this as this appears to me as too cumbersome. In R I could just do a simple:

我通过基本上创建 3 个包含我想要的列的列表来进行子集化,但我认为必须有更好的方法来做到这一点,因为这在我看来太麻烦了。在 RI 中可以做一个简单的:

df01[c(1:2,4,9:10)]

Again, this may be just the way it is, but given my status as a python "newbie', Im interested to know if there is a better more concise way.

同样,这可能只是它的方式,但考虑到我作为 python“新手”的身份,我很想知道是否有更好更简洁的方法。

Thanks,

谢谢,

回答by Dodge

Remember that Python is zero indexed. Here you have ten columns but the max index will be nine. You can do this in pandaswith the following:

请记住,Python 是零索引的。这里有 10 列,但最大索引为 9。您可以pandas使用以下方法执行此操作:

df01.iloc[:, [0,1,3,8,9]]

   a  b  d  i  j
0  6  0  9  9  0
1  7  9  9  4  4
2  1  3  4  0  4
3  4  6  1  7  0
4  4  6  3  1  2
5  5  6  2  9  1
6  0  6  6  6  2
7  8  2  0  5  5
8  4  7  5  8  4
9  2  3  6  2  9