1

What I have:

series = ['foo', 'bar', 'baz', 'foo', 'baz', 'foo' ]
column = [1, 2, -3, -4, 5, -6]


list = [column[function(x)].count() for x in series]

list:
foo = 3
bar = 1
baz = 2

Works fine, each instance in series is counted.

Want only positive number instances counted as well, so:

list = [column[function(x)].count() for x in series if (x := function(x)) >= 0]

list:

foo = 1
bar = 1
baz = 1

Discovered Walrus Operator, but x in my case is a string, perhaps the core problem?

I do get a syntax error with Walrus portion of code.

I need both total & positive number counts, creating say a "total" & "positive totals" columns in function seems clunky, is there a way to do this with list comprehension.

Thank you in advance for your assistance.

Rayl54292
  • 83
  • 2
  • 6

2 Answers2

0

Since you tagged pandas:

pd.Series(column).gt(0).groupby(series).agg({'count','sum'})

Output:

     count  sum
bar      1    1
baz      2    1
foo      3    1
Quang Hoang
  • 117,517
  • 10
  • 34
  • 52
0

You are calling function(x) where x is the result of function(x) already. Try:

vals = [column[y].count() for x in series if (y := function(x)) >= 0]

Notes:

  1. Use a different variable name than x so that it is less confusing (this is probably also the source of your syntax error).
  2. list is a type name, choose a different name for the list of values.