请选择单独的列

2024-04-19 21:59:22 发布

您现在位置:Python中文网/ 问答频道 /正文

给定以下数据帧:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3],'b':[4,5,6],'c':[1,2,3],'d':[4,5,6]})

df
   a  b  c  d
0  1  4  1  4
1  2  5  2  5
2  3  6  3  6

我只想按列索引位置选择列a、c和d。 我尝试了以下方法但没有成功:

df[df.columns[0],df.columns[-2:]]

我可能可以通过普通的Python找到答案,但我想知道熊猫是否有捷径。你知道吗


Tags: columns数据方法答案importdataframepandasdf
1条回答
网友
1楼 · 发布于 2024-04-19 21:59:22

使用索引append

df.loc[:,df.columns[[0]].append(df.columns[-2:])]
Out[1363]: 
   a  c  d
0  1  1  4
1  2  2  5
2  3  3  6

或者只是使用.iloc

df.iloc[:,[0,2,3]] 

嗯,也许np.r_

df.iloc[:,np.r_[0,-2:0]]
Out[1371]: 
   a  c  d
0  1  1  4
1  2  2  5
2  3  3  6

相关问题 更多 >