簡體   English   中英

替換 pandas 系列中的負值

[英]Replace negative values in pandas Series

我有一個類似以下的系列:

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

我想用 0 替換所有負值,但是我只能找到適用於數據框的方法。 我嘗試使用s.masks.loc但是我遇到了混合類型的問題。

預計 output 將是

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

使用pd.to_numeric + Series.lt創建一個 boolean 掩碼,然后使用此mask替換系列中的0值:

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

結果:

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

您可以使用字典理解:

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()}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM