按索引删除多个Pandas列

2024-04-29 16:09:31 发布

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

我有一个大熊猫数据框(>;100列)。我需要删除不同的列,我希望有一种使用旧列的方法

df.drop(df.columns['slices'],axis=1)

我做了如下选择:

a = df.columns[3:23]
b = df.colums[-6:]

因为ab表示要删除的列集。

以下

list(df)[3:23]+list(df)[-6:]

生成正确的选择,但我不能用drop实现它:

df.drop(df.columns[list(df)[3:23]+list(df)[-6:]],axis=1)

ValueError: operands could not be broadcast together with shapes (20,) (6,)

我环顾四周,却找不到答案。

Selecting last n columns and excluding last n columns in dataframe

(以下与我收到的错误有关):

python numpy ValueError: operands could not be broadcast together with shapes

这一个让人觉得他们也有类似的问题,但“切片”并不是分开的: Deleting multiple columns based on column names in Pandas

干杯


Tags: columnsdfwithnotbelistdropcould
3条回答

您可以使用这个简单的解决方案:

cols = [3,7,10,12,14,16,18,20,22]
df.drop(df.columns[cols],axis=1,inplace=True)

结果是:

    0   1   2   4   5   6   8   9    11  13      15     17      19       21
0   3   12  10  3   2   1   7   512  64  1024.0  -1.0   -1.0    -1.0    -1.0
1   5   12  10  3   2   1   7   16   2   32.0    32.0   1024.0  -1.0    -1.0
2   5   12  10  3   2   1   7   512  2   32.0    32.0   32.0    -1.0    -1.0
3   5   12  10  3   2   1   7   16   1   32.0    64.0   1024.0  -1.0    -1.0

如您所见,具有给定索引的列已全部删除。

如果我们假设您有A、B、C……等,您可以用数组中的列的名称替换int值,您可以这样替换cols中的int值,例如:

cols = ['A','B','C','F']

可以使用^{}无缝组合多个范围/切片:

from string import ascii_uppercase

df = pd.DataFrame(columns=list(ascii_uppercase))

idx = np.r_[3:10, -5:0]

print(idx)

array([ 3,  4,  5,  6,  7,  8,  9, -5, -4, -3, -2, -1])

然后可以使用idx为列编制索引并馈送到^{}

df.drop(df.columns[idx], axis=1, inplace=True)

print(df.columns)

Index(['A', 'B', 'C', 'K', 'L', 'M', 'N',
       'O','P', 'Q', 'R', 'S', 'T', 'U'], dtype='object')

IIUC:

a = df.columns[3:23].values.tolist()
b = df.colums[-6:].values.tolist()

a.extend(b)
df.drop(a,1,inplace=True)

相关问题 更多 >