Home > Back-end >  Lambda How to return count =1 Pandas
Lambda How to return count =1 Pandas

Time:08-05

I want to apply lambda function on my dataset but it's not returning a count value. If the x is higher than 5, count = count 1 and it should be return the count:

enter image description here

b = a.apply(lambda x, count=0: count=count 1 if x==5)
b

CodePudding user response:

IIUC, you can use:

df = pd.DataFrame({'a':range(10)})
df.apply(lambda x: [x 1 if x >= 5 else x for x in df.a])

Output:

   a
0  0
1  1
2  2
3  3
4  4
5  5
6  6
7  7
8  8
9  9

CodePudding user response:

You have several options to count elements in a list that fit into a condition, like:

countCondition = len(list(filter(lambda x: x == 5, a)))

or

countCondition = len([x for x in a if x == 5])

CodePudding user response:

You need to call a function that does the comparison and returns the value, e.g.:

a = {'a': [1, 2, 3, 4, 6, 6]}
a = pd.DataFrame(a)

count = 0
def count_x(x):
    if x > 5:
        global count
        count  = 1

    return count

b = a['a'].apply(lambda x: count_x(x))

note that global count to prevent passing count as parameter.

print(b) gives:

0    0
1    0
2    0
3    0
4    1
5    2

CodePudding user response:

Check Below code based on your statement x is higher than 5:

import pandas as pd

df = pd.DataFrame({'a':[1,2,3,4,5,6,1,7,3,8,2]})

df.assign(flag = np.where(df['a']>5,1,0)).\
assign(count=lambda x: x.flag.cumsum())[['a','count']]

Output:

enter image description here

  • Related