How to compare if the value of a dataframe column is in an array if you are creating a new column with that value?

Asked

Viewed 31 times

-1

lista = array(['NF', 'BT', 'C', 'N', 'I', 'IP',
       'Aa', 'Sa', 'Gl', 'Et', 'To', 'Hr',
       'Cr', 'Ro', 'X', 'Oa', 'Ml', 'Me'], dtype=object)

"DATAFRAME" 
  x_1 x_2
0  NF  0
1  A   0 
2  B   0 
3  KK  0 
4  Gl  0
5  Oa  0

The desired exit would be this below :

  x_1 x_2
0  NF  NF
1  A   0 
2  B   0 
3  KK  0 
4  Gl  Gl
5  Oa  Oa

If the column value is equal to any given array it returns the new column with this value otherwise returns 0

  • I’m sorry I didn’t understand how you got from the list to the dataframe? Or compare list with a column of a dataframe whose code is not present in the question?

1 answer

0

If I understand correctly, use the isin()

Creating list and dataframe for testing

>>> lista = array(['NF', 'BT', 'C', 'N', 'I', 'IP',
...        'Aa', 'Sa', 'Gl', 'Et', 'To', 'Hr',
...        'Cr', 'Ro', 'X', 'Oa', 'Ml', 'Me'], dtype=object)

>>> df = pd.DataFrame({"x_1": ["NF", "A", "B", "KK", "Gl", "Oa"]})

Creating new column

>>> df["x_2"] = df[df["x_1"].isin(lista)]

>>> df
  x_1  x_2
0  NF   NF
1   A  NaN
2   B  NaN
3  KK  NaN
4  Gl   Gl
5  Oa   Oa

Filling Nan with 0 (zero)

>>> df["x_2"].fillna(0, inplace=True)

>>> df
  x_1 x_2
0  NF  NF
1   A   0
2   B   0
3  KK   0
4  Gl  Gl
5  Oa  Oa

Browser other questions tagged

You are not signed in. Login or sign up in order to post.