Home > Net >  value column in other column containing list of values
value column in other column containing list of values

Time:10-04

Column A contains strings. Column B contains list of strings. I would like to know how many times is the value of A in the column B.

I have

A B
k [m]
c [k,l,m]
j [k,l]
e [e,m]
e [e,m,c,e]

I would like this output:

C
0
0
0
1
2

CodePudding user response:

You can use apply on row then use .count list like below. Try this:

>>> df = pd.DataFrame({'A': ['k', 'c', 'j', 'e', 'e'],'B': [['m'],['k','l','m'],['k','l'],['e','m'],['e','m','c','e']]})
>>> df['C'] = df.apply(lambda row: row['B'].count(row['A']), axis=1)
>>> df

           A    B               C
0          k    [m]             0
1          c    [k, l, m]       0
2          j    [k, l]          0
3          e    [e, m]          1
4          e    [e, m, c, e]    2
  • Related