Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

python - Drop columns if rows contain a specific value in Pandas

I am starting to learn Pandas. I have seen a lot of questions here in SO where people ask how to delete a row if a column matches certain value.

In my case it is the opposite. Imagine having this dataframe:

Dataframe

Where you want to know is, if any column has in any of its row the value salty, that column should be deleted, having as a result:

Dataframe 2

I have tried with several similarities to this:

if df.loc[df['A'] == 'salty']:
   df.drop(df.columns[0], axis=1, inplace=True)

But I am quite lost at finding documentation onto how to delete columns based on a row value of that column. That code is a mix of finding a specific column and deleting always the first column (as my idea was to search the value of a row in that column, in ALL columns in a for loop.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Perform a comparison across your values, then use DataFrame.any to get a mask to index:

df.loc[:, ~(df == 'Salty').any()]

If you insist on using drop, this is how you need to do it. Pass a list of indices:

df.drop(columns=df.columns[(df == 'Salty').any()])

df = pd.DataFrame({
    'A': ['Mountain', 'Salty'], 'B': ['Lake', 'Hotty'], 'C': ['River', 'Coldy']})
df
          A      B      C
0  Mountain   Lake  River
1     Salty  Hotty  Coldy

(df == 'Salty').any()
A     True
B    False
C    False
dtype: bool

df.loc[:, ~(df == 'Salty').any()]
       B      C
0   Lake  River
1  Hotty  Coldy

df.columns[(df == 'Salty').any()]
# Index(['A'], dtype='object')

df.drop(columns=df.columns[(df == 'Salty').any()])
       B      C
0   Lake  River
1  Hotty  Coldy

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...