Home > other >  How to check values from list in DataFrame column and insert value by condition?
How to check values from list in DataFrame column and insert value by condition?

Time:05-24

for example, I have the next list:

l = ['a', 'x', 't']

and the DataFrame:

a = [{'sufix': 'a', 'qty': 5}, {'sufix': 'b', 'qty': 2}, {'sufix': 'c', 'qty': 7}, {'sufix': 'x', 'qty': 9}, {'sufix': 't', 'qty': 4}, {'sufix': 'p', 'qty': 1}]
df = pd.DataFrame(a)
print(df)

What I need, if values from list -> l are in column df['sufix'] -> create new column df['yes'] and put value from column df['qty'], else df['yes'] = 0

I need the next result:

enter image description here

CodePudding user response:

If I understand you correctly, probably something like this:

df['yes'] = df['qty'][df['sufix'].isin(l)]
df['yes'] = df['yes'].fillna(0)

CodePudding user response:

Just like this:

df['yes'] = df.sufix.isin(l) * df.qty

The boolean value returned by isin() for the sufix column will be converted to 0 for False, 1 for True, and multiplied by the value in qty.

Output:

  sufix  qty  yes
0     a    5    5
1     b    2    0
2     c    7    0
3     x    9    9
4     t    4    4
5     p    1    0

CodePudding user response:

from tokenize import String
import pandas as pd
import numpy as np
l = ['a', 'x', 't']
a = [{'sufix': 'a', 'qty': 5}, {'sufix': 'b', 'qty': "ww"}, {'sufix': 'c', 'qty': "a"}, {'sufix': 'x', 'qty': "9"}, {'sufix': 't', 'qty': 4}, {'sufix': 'p', 'qty': 1}]
df = pd.DataFrame(a).assign(yes=lambda x: np.where(x["qty"].isin(l), x["qty"],0))

To also deal with text.

  • Related