簡體   English   中英

Python pandas循環值以兩列為條件

[英]Python pandas loop value conditional on two columns

在我的數據框“數據”中,我有兩列'trend'和'rtrend'

trend值為-1,0和1。

def newfunc(a):

j = -1

for i in a:

    j = j+1
    x = (j-1)

    if data.iloc[j]['trend'] != 0:

        return data.iloc[j]['trend'] 

    if data.iloc[j]['trend'] == 0:

        return data.iloc[x]['rtrend']

如果trend等於-1或1,那么我想將rtrend列值設置為trend

如果trend等於0,則將rtrend設置rtrend等於數據rtrend上方顯示的該系列中的最后一個值。

data['rtrend'] = newfunc(data['trend'])

對於整個系列,它當前返回的全部為0。

請有人指出我正確的方向嗎? 我敢肯定必須有更好的方法來做到這一點。 (我已經嘗試過np.where() ,它似乎沒有做我想要的事情)。

不要做一個程序緩慢for循環。 做矢量化方法。 只需將非零數據復制到新的rtrend列中,然后轉發填充數據:

df['rtrend'] = df[df.trend!=0]['trend']

df
Out[21]: 
   trend    b    c  rtrend
a   -1.0  1.0 -1.0    -1.0
c    0.0 -1.0  1.0     NaN
e    1.0 -1.0 -1.0     1.0
f   -1.0  1.0 -1.0    -1.0
h   -1.0  1.0  1.0    -1.0

df['rtrend'].ffill()
Out[22]: 
a   -1.0
c   -1.0
e    1.0
f   -1.0
h   -1.0
Name: rtrend, dtype: float64

暫無
暫無

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

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