从熊猫数据框中选择非连续和连续的列

时间:2020-07-04 18:49:49

标签: python python-3.x pandas

我正在尝试从pandas DataFrame中选择多个列,但这样做有麻烦。假设我有以下DataFrame:

import pandas as pd
import numpy as np

cols = ['test','one','two','three','four','five','six','seven','eight','nine','ten']
df = pd.DataFrame(np.random.rand(10,11).round(2),columns=cols)

我要选择列testtwofourfivesixseveneight < / p>

我知道,如果我想选择单个列,

df[['test','two']]

如果我要选择连续的列,

df.loc[:,'four':'eight']

工作正常,但是如何将两者简洁地结合在一起?

我意识到对于这个具体示例,写作

df[['test', 'two', 'four', 'five', 'six', 'seven', 'eight']]

也可以使用,但是我想知道是否有一种方法可以利用大多数列在此处是连续的这一事实,从而节省了编写所有列的时间。

1 个答案:

答案 0 :(得分:3)

np.r_ @Pooja的建议,但使用 get_loc get_indexer 基于标签的切片:

a = ['test','two']
b = ['four','eight']
idx= np.r_[df.columns.get_indexer(a),df.columns.get_loc(b[0]):df.columns.get_loc(b[1])+1]
print(df.iloc[:,idx])

   test   two  four  five   six  seven  eight
0  0.11  0.91  0.13  0.99  0.17   0.56   0.21
1  0.70  0.94  0.72  0.48  0.53   0.99   0.27
2  0.37  0.03  0.81  0.18  0.47   0.94   0.77
3  0.13  0.69  0.16  0.80  0.02   0.42   0.48
4  0.79  0.91  0.97  0.83  0.20   0.32   0.58
5  0.12  0.86  0.44  0.01  0.71   0.65   0.03
6  0.77  0.31  0.21  0.73  0.70   0.95   0.11
7  0.09  0.91  0.45  0.35  0.91   0.21   0.92
8  0.28  0.32  0.73  0.93  0.97   0.03   0.93
9  0.55  0.77  0.02  0.18  0.65   0.50   0.85