繁体   English   中英

python dataframe pandas 使用列名删除多个列

[英]python dataframe pandas drop multiple column using column name

我知道要删除您使用的列df.drop('column name', axis=1, inplace =True)

文件格式为.csv文件

我想以稳健的方式将上述语法用于大型数据集和更多

假设我有 500 列,我想使用列名而不是索引来保留第 100 到 140 列,并且 rest 想要删除,我将如何编写上述语法以便实现我的目标以及 100 到 140 列,我想要按列名删除第 105、108,110 列

df = df.loc[:, 'col_100_name' : 'col_140_name']

.loc始终选择使用两端(包括两端)。 在这里,我选择所有行,并且只选择您想要 select 的列(按名称)。

在此之后(或之前 - 没关系),您可以像往常一样按名称删除其他列:

df.drop(['col_105_name', 'col_108_name', 'col_110_name'], axis=1, inplace=True)

如果您希望使用切片和显式列名的组合来 select 列:

cols_in_the_slice = df.loc[:, 'col_100_name' : 'col_140_name'].columns
other_cols = pd.Index(['col_02_name', 'col_04_name'])
all_cols = other_cols.union(cols_in_the_slice , sort=False)

df = df[all_cols]

Union 将cols_in_the_slice的新(尚未遇到)元素附加到other_cols的末尾。 它默认排序,所以我指定sort=False不排序。 然后我们选择所有这些列。

顺便说一句,您还可以在此处删除您不希望拥有的列名。

如果您知道列名,则可以使用.drop ,如果您知道它们在此索引中的位置,则可以使用.delete

cols_in_the_slice = cols_in_the_slice.drop(['col_105_name', 'col_108_name', 'col_110_name'])

我还建议查看Pandas User Guide on Indexing and selection data

不要使用字符串参数作为列名,而是使用引用要删除的列名的字符串列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM