vendredi 23 juillet 2021

Pandas If Else condition on multiple columns

I have a df as:

df:
        col1       col2       col3        col4        col5
0       1.36       4.31       7.66           2           2
1       2.62       3.30       2.48           2           1
2       5.19       3.58       1.62           0           2
3       2.06       3.16       3.50           1           1
4       2.19       2.98       3.38           1           1

I want

col6 to return 1 when (col4 > 1 and col5 > 1) else 0

and

col7 to return 1 when (col4 > 1 and col5 > 1 and col 4 + col5 > 2) else 0

I am trying

df.loc[df['col4'] > 0, df['col5'] > 0, 'col6'] = '1'

however I am getting the error:

File "pandas\_libs\index.pyx", line 269, in pandas._libs.index.IndexEngine.get_indexer
  File "pandas\_libs\hashtable_class_helper.pxi", line 5247, in pandas._libs.hashtable.PyObjectHashTable.lookup
TypeError: unhashable type: 'Series'

How can I perform this operation?

Aucun commentaire:

Enregistrer un commentaire