pandas 如何使用python选择前X列和最后Y列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42632029/
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
how to use python to select first X columns and last Y columns
提问by Gavin
I am trying to select column 1 to 8 and the last column from a data frame. I have some dumb way to do that
我正在尝试从数据框中选择第 1 到第 8 列和最后一列。我有一些愚蠢的方法来做到这一点
step 1: select first 8 column
第 1 步:选择前 8 列
df1 = df[df.columns[range(9)]]
step 2: select last column
第 2 步:选择最后一列
df2 = df[df.columns[-1]]
step 3: combine step1 and step2
步骤3:结合步骤1和步骤2
df1.join(df2)
is there a better way to do that in one step instead of 3 steps?
有没有更好的方法可以一步而不是 3 步做到这一点?
回答by DYZ
Use smart column indexing:
使用智能列索引:
df.iloc[:, list(range(9)) + [-1]]
回答by mukiljchandiran
Use Concatfrom Pandas. This works as same as CBIND.
使用Pandas 中的Concat。这与CBIND相同。
new_df = pd.concat([df.iloc[:,0:8],df.iloc[:,-1:]],axis = 1)
回答by bieniek
In addition to @DYZ answer. You can use another combination to select first and few last columns
除了@DYZ 的回答。您可以使用另一种组合来选择第一列和最后几列
df.iloc[ :[1] + list(range(-10, 0)]
回答by pdel5
Try using head/tail in the dataframe.
尝试在数据框中使用头/尾。
print(df.head(8))
print(df.tail(8))