可以使用numpy.r_
爲指數的級聯,但它僅適用於位置,因此需要get_loc
或searchsorted
+ iloc
:
df = pd.DataFrame(np.arange(8).reshape(1, 8), columns = list('abcdefgh'))
print (df)
a b c d e f g h
0 0 1 2 3 4 5 6 7
b = df.columns.get_loc('b')
d = df.columns.get_loc('d')
f = df.columns.get_loc('f')
h = df.columns.get_loc('h')
print (b,d,f,h)
1 3 5 7
b = df.columns.searchsorted('b')
d = df.columns.searchsorted('d')
f = df.columns.searchsorted('f')
h = df.columns.searchsorted('h')
print (b,d,f,h)
1 3 5 7
df = df.iloc[:, np.r_[b:c+1, f:h+1]]
print (df)
b c d f g h
0 1 2 3 5 6 7
是一樣的:
df = df.iloc[:, np.r_[1:4, 5:8]]
print (df)
b c d f g h
0 1 2 3 5 6 7
df = df.iloc[:, np.r_['b':'d', 'f':'h']]
print (df)
#TypeError: unsupported operand type(s) for -: 'str' and 'str'
與loc
+ join
另一種解決方案:
df = df.loc[:,'b':'d'].join(df.loc[:,'f':'h'])
print (df)
b c d f g h
0 1 2 3 5 6 7