![](/img/trans.png)
[英]Pandas DataFrame replace negative values with latest preceding positive value
[英]Replace negative values and 'blocks" of consecutive zeros up to first positive value in pandas series with NaN
我有一個熊貓數據框,我想識別所有負值並將其替換為NaN。 此外,跟隨負值的所有零也應替換為NaN,直到出現第一個正值。
我認為應該可以對數據幀中的所有負值使用for循環來實現我的目標。
例如,對於索引標簽為1737的負值,我可以使用如下所示的內容:
# list indexes that follow the negative value
indexes = df['counter_diff'].loc[1737:,]
# find first value greater than zero
first_index = next(x for x, val in enumerate(indexes) if val > 0)
然后使用NaN填充從索引1737到first_index
的值。
但是,我的數據幀很大,因此我想知道是否有可能提出一種利用熊貓計算效率更高的方法。
這是輸入的示例:
# input column
In[]
pd.Series({0 : 1, 2 : 3, 3 : -1, 4 : 0, 5 : 0, 7 : 1, 9 : 3, 10 : 0, 11 : -2, 14 : 1})
Out[]
0 1
2 3
3 -1
4 0
5 0
7 1
9 3
10 0
11 -2
14 1
dtype: int64
和所需的輸出:
# desired output
In[]
pd.Series({0 : 1, 2 : 3, 3 : np.nan, 4 : np.nan, 5:np.nan, 7:1, 9:3, 10:0, 11 : np.nan, 14:1})
Out[]
0 1.0
2 3.0
3 NaN
4 NaN
5 NaN
7 1.0
9 3.0
10 0.0
11 NaN
14 1.0
dtype: float64
任何幫助,將不勝感激!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.