0

I have this df:

A B C D a d a z b c z c 

My goal is to pull out the column names where df == 'z' so I used:

df['ColumnNames'] = df.where(df=='z' ).stack().reset_index().groupby('level_0')['level_1'].apply('+ '.join) 

It used to work fine; however today I got an error saying: "TypeError: Could not compare ['z'] with block values"

Does anyone know why this happens? Many thanks!

4
  • I wasn't able to reproduce the error you have. Did you make any changes to your python packages in recent days? Have you tried to re-run your code or restart your jupyter notebook? What's your python and pandas version? Commented Feb 27, 2018 at 21:19
  • 2
    My guess is that you have a version of pandas that is borking when comparing int to str. Try df.astype(object) == 'z' Commented Feb 27, 2018 at 21:20
  • Thank you for all the help. I pulled the data from SQL maybe something changed in the back end but I was about to fix it now. Commented Feb 27, 2018 at 21:25
  • @piRSquared feel free to modify it :-) make it community :-) Commented Feb 27, 2018 at 21:30

1 Answer 1

2

Your code working fine on my side, check whether contain space in your df , also we short it with

df[df=='z'].stack() Out[216]: 0 D z 1 C z dtype: object df[df=='z'].stack().index.get_level_values(1) Out[218]: Index(['D', 'C'], dtype='object') 

From the Comment above by PiR

My guess is that you have a version of pandas that is borking when comparing int to str. Try df.astype(object) == 'z'

Sign up to request clarification or add additional context in comments.

2 Comments

it wasn't a space or anything. I think it must be one of the data type problem. I was about to fix it now with df.astype(str) =='z'. It's weird because I just got the problem today but before it was fine.
@TylerNG aha , That is ok , I will make this answer to community and adding Pir 's solution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.