numpy where search multiple conditions with a precomputed series

Viewed 71

I have a list with a multiple series with booleans and pandas DataFrame. The number of series in the list varies.

s1 = {Series: (4,)} (0, True) (1, True) (2, True) (3, True)
s2 = {Series: (4,)} (0, True) (1, True) (2, True) (3, False)
list_with_series = [s1, s2]

df = {DataFrame: (4, 8)}

I want to use numpy.where to add a column to DataFrame with a tag like this:

df['Tag'] = numpy.where(' & '.join(list_with_series), 'Tag_name', '')

When I try to join series, I get this error:

TypeError: sequence item 0: expected str instance, Series found

I cant directly specify series like numpy.where(s1 & s2), because number of series are dynamic. I also try to use numpy because it is less memory intensive.

What is the best way to match and tag rows in DataFrame, not changing of using precomputed series with booleans? Is it even possible to use numpy in such scenario?

Thank you!

1 Answers

When you write ' & '.join(...) in this case, the expectancy is that you'll pass strings, not series. This is the error.

In this case, you could use:

import numpy as np

np.logical_and.reduce([s.values for s in list_with_series])
Related