Manuel
Manuel

Reputation: 591

Replace negative values in pandas Series

I've got a series like the following:

s = pd.Series({'val1': 'a', 'val2': 'b', 'other_val1': 1, 'other_val2': -1, 'other_val3': 3, 'other_val4': -1.5})

val1            a
val2            b
other_val1      1
other_val2      0
other_val3      3
other_val4   -1.5
dtype: object

I want to replace all negative values by 0, however I could only find methods that work with dataframes. I tried to play around with s.mask and s.loc however I had problems with the mixed types.

Expected output would be

val1          a
val2          b
other_val1    1
other_val2    0
other_val3    3
other_val4    0
dtype: object

Upvotes: 1

Views: 484

Answers (2)

A. Abramov
A. Abramov

Reputation: 1865

You can use dictionary comprehension:

series = {'val1': 'a', 'val2': 'b', 'other_val1': 1, 'other_val2': -1, 'other_val3': 3, 'other_val4': -1.5}
replaced_series = {k:0 if str(v).lstrip('-+').isdigit() and int(v)<0 else v for (k,v) in series.items()}

Upvotes: 0

Shubham Sharma
Shubham Sharma

Reputation: 71689

Use pd.to_numeric + Series.lt to create a boolean mask, then use this mask to substitue 0 values in the series:

mask = pd.to_numeric(s, errors='coerce').lt(0)
s.loc[mask] = 0

Result:

val1          a
val2          b
other_val1    1
other_val2    0
other_val3    3
other_val4    0
dtype: object

Upvotes: 3

Related Questions