1

How can I select the columns in the dataframe which the column names is not belong to a list?

For example:

I have the following input and I would like to select columns which columns names does not belong to b

#input
a=pd.DataFrame({
    '0':[10,10,10,10,10],
    '1':[2,3,8,10,11],
    '2':[0,1,2,3,4],
    '3':[13,12,14,14,13],
    '4':[15,13,17,18,19],
    '5':[10,2,3,4,6]
})
b=[2,3,4]

#output
output=pd.DataFrame({
    '0':[10,10,10,10,10],
    '1':[2,3,8,10,11],
    '5':[10,2,3,4,6]
})
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
LilyBre
  • 11
  • 2
  • Does this answer your question? [Selecting/excluding sets of columns in pandas](https://stackoverflow.com/questions/14940743/selecting-excluding-sets-of-columns-in-pandas) – nlivingstone Mar 17 '23 at 17:25

3 Answers3

2

Here the catch is that your elements in b are integers while a columns are strings:

you can convert your b values to string then:

#input
a=pd.DataFrame({
    '0':[10,10,10,10,10],
    '1':[2,3,8,10,11],
    '2':[0,1,2,3,4],
    '3':[13,12,14,14,13],
    '4':[15,13,17,18,19],
    '5':[10,2,3,4,6]
})
b=[2,3,4]

new_b = [str(x) for x in b]

a[a.columns.difference(new_b)]  # or a[a.columns.difference(map(str, b))]

#Output
    0   1   5
0   10  2   10
1   10  3   2
2   10  8   3
3   10  10  4
4   10  11  6

One more way is:

a[a.columns[~a.columns.isin(new_b)]]

    0   1   5
0   10  2   10
1   10  3   2
2   10  8   3
3   10  10  4
4   10  11  6
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
1

Convert b to strings, Iterate over a.columns and check which element in a.columns is not in b

a=pd.DataFrame({
    '0':[10,10,10,10,10],
    '1':[2,3,8,10,11],
    '2':[0,1,2,3,4],
    '3':[13,12,14,14,13],
    '4':[15,13,17,18,19],
    '5':[10,2,3,4,6]
})
})
b=['2','3','4']
b = [str(x) for x in b]

chosen_columns = [e for e in a.columns if e not in b]

output = a[chosen_columns]
Yannick Funk
  • 1,319
  • 10
  • 23
1

You can use drop and create a new dataframe:

b = [str(i) for i in b]
output = a.drop(columns=b)


# Output
    0   1   5
0  10   2  10
1  10   3   2
2  10   8   3
3  10  10   4
4  10  11   6
Hamzah
  • 8,175
  • 3
  • 19
  • 43