使用Pandas切割多个列范围

问题描述 投票:0回答:1

假设我在数据集中有20个列,并且我想使用19作为输入。和输入列是1:10和12:20的列。我想使用第11列作为输出。那么如何使用熊猫来提供这种范围呢?

例如:Example Data Set

考虑上面的数据,它有4列,但我只需输入3列,但这些列是b,d,e,我想跳过c列。现在我使用input = dftrain.loc [:,:'e']来考虑所有4列。

python pandas dataframe slice
1个回答
1
投票

选项1 np.r_

idx = np.r_[0:11, 12:20]

idx
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 12, 13, 14, 15, 16, 17,
       18, 19])

将此传递给iloc -

df.iloc[:, 11] = df.iloc[:, idx].sum(axis=1) # sum, for example

选项2 pd.IndexSlice

idx = pd.IndexSlice[0:11, 12:20]

idx
(slice(0, 11, None), slice(12, 20, None))

您可以像以前一样使用idx

© www.soinside.com 2019 - 2024. All rights reserved.