简体   繁体   English

从 pandas DataFrame 中删除名称包含特定字符串的第一个(或任何第 n 个)列

[英]Drop the first (or any nth) column whose name contains a specific string from pandas DataFrame

Let's say I have a pandas DataFrame as follows:假设我有一个 pandas DataFrame 如下:

df = pd.DataFrame([[1,2,3,4,5],[6,7,8,9,10]],columns=['a1693','b1124','b113','a2609', 'a1'])

I want to drop, for example, b1124 .例如,我想删除b1124 How do I do it?我该怎么做?

I can get the column as a pd.Series by using the following code.我可以使用以下代码将该列作为 pd.Series 获取。

df.loc[:,df.columns.str.contains('b')].iloc[:,0]

But I don't know how to drop it from df .但我不知道如何从df中删除它。

Also, if I want to do the same for multiple columns, ie drop a1693 and b1124 , how do I do that as well?另外,如果我想对多个列执行相同的操作,即删除a1693b1124 ,我该怎么做呢?

add filter添加过滤器

df = df.drop(df.columns[df.columns.str.contains('b')][0],1)
   a1693  b113  a2609  a1
0      1     3      4   5
1      6     8      9  10
In [28]: N = 0

In [29]: df.drop(df.columns[np.where(df.columns.str.contains("b")==True)[0][N]], axis=1)
Out[29]:
   a1693  b113  a2609  a1
0      1     3      4   5
1      6     8      9  10

In [30]: N = 1

In [31]: df.drop(df.columns[np.where(df.columns.str.contains("b")==True)[0][N]], axis=1)
Out[31]:
   a1693  b1124  a2609  a1
0      1      2      4   5
1      6      7      9  10

暂无
暂无

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

相关问题 从 Pandas DataFrame 中删除名称包含特定字符串的列 - Drop columns whose name contains a specific string from pandas DataFrame 从名称包含特定字符串的列创建新列 - creating new column from columns whose name contains a specific string 查找名称包含特定字符串的列 - Find column whose name contains a specific string Python pandas dataframe:在数组列中,如果第一项包含特定字符串,则从数组中删除该项 - Python pandas dataframe : In an array column, if first item contains specific string then remove that item from array 删除 pandas dataframe 中的每 n 列 - Drop every nth column in pandas dataframe 如果一列的字符串包含 pandas dataframe 中另一列的单词,如何删除整行 - How to drop entire row if string of one column contains the word from another column in pandas dataframe 如何从熊猫数据框中删除行,其中任何列都包含我不想要的符号 - How to drop rows from a pandas dataframe where any column contains a symbol I don't want Pandas 如果列包含字符串,则从另一列获取唯一值并从 dataframe 中删除行 - Pandas if colum contains string then get unique value from another column and drop rows from dataframe 使用包含空格的列名称或使用包含空格的列名称的drop方法查询Pandas DataFrame - Querying Pandas DataFrame with column name that contains a space or using the drop method with a column name that contains a space 如果列包含任何指定的部分字符串,Pandas Dataframe保留行 - Pandas Dataframe Keep Row If Column Contains Any Designated Partial String
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM