Home > Mobile >  how to compare variable in different columns pandas
how to compare variable in different columns pandas

Time:11-28

I want to compare three variable in three dataframe columns. but it gave me an error TypeError: unhashable type: 'Series'. below is my code

import pandas as pd
df = pd.DataFrame(columns=['Entry','Middle','Exit'])
entry_value = '17.98'
middle_value = '12.16'
exit_value = '1.2'
df = df.append({'Entry' : entry_value , 'Middle' : middle_value, 'Exit' : exit_value}, ignore_index = True)
entry_value = '19.98'
middle_value = '192.16'
exit_value = '1.1'
if entry_value in {df['Entry'] , df['Middle'] , df['Exit']} :
    print('entry')
elif middle_value in {df['Entry'] , df['Middle'] , df['Exit']} :
    print('middle')
elif exit_value in {df['Entry'] , df['Middle'] , df['Exit']} :
    print('exit')
else:
    print('wawo')`

CodePudding user response:

You can search for a column but if you want to search for multiple columns you must either convert them to a single list or define them as a single series.

if entry_value in df[['Entry','Middle','Exit']].stack().to_list():
    print('entry')
elif middle_value in df[['Entry','Middle','Exit']].stack().to_list():
    print('middle')
elif exit_value in df[['Entry','Middle','Exit']].stack().to_list():
    print('exit')
else:
    print('wawo')

If you are searching all columns, you do not need to define individual column names:

#dont use
#df[['Entry','Middle','Exit']].stack()

#use
#df.stack()
if entry_value in df.stack().to_list():
    print('entry')
elif middle_value in df.stack().to_list():
    print('middle')
elif exit_value in df.stack().to_list():
    print('exit')
else:
    print('wawo')

CodePudding user response:

I suggest you to use pandas.DataFrame.isin to check if any of the columns selected contain a certain value.

Try this :

cols= ['Entry', 'Middle', 'Exit']

if any(df[cols].isin([entry_value])):
    print('entry')
elif any(df[cols].isin([middle_value])):
    print('middle')
elif any(df[cols].isin([exit_value])):
    print('exit')
else:
    print('wawo')

NB: Not sure why you're assigning different values to the same variables when constructing your datarame but you should know that pandas.DataFrame.append is deprecated.

FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.

  • Related