[英]pandas dataframe conditional population of a new column
我正在處理 pandas DataFrame 中的列(趨勢)。下面是我的源 DataFrame。目前我已將其設置為 0。
我想用來填充趨勢列的邏輯如下
如果 df['Close'] > df.shift(1)['Down'] 那么 1
如果 df['Close'] < df.shift(1)['Up'] 那么 -1
如果上述任何一個條件不滿足,則 df.shift(1)['Trend']。 如果此值為 NaN,則將其設置為 1。
以上純文本代碼,
更新
文本形式的數據
Close Up Down Trend
3.138 NaN NaN 0
3.141 NaN NaN 0
3.141 NaN NaN 0
3.130 NaN NaN 0
3.110 NaN NaN 0
3.130 3.026432 3.214568 0
3.142 3.044721 3.214568 0
3.140 3.047010 3.214568 0
3.146 3.059807 3.214568 0
3.153 3.064479 3.214568 0
3.173 3.080040 3.214568 0
3.145 3.080040 3.214568 0
3.132 3.080040 3.214568 0
3.131 3.080040 3.209850 0
3.141 3.080040 3.209850 0
3.098 3.080040 3.205953 0
3.070 3.080040 3.195226 0
預計 output
根據滿足的條件,我們可以使用numpy.select
到 select 的值。 然后將numpy.select
的結果傳遞給fillna
以用它填充缺失的“趨勢”值(這用於不丟失現有的“趨勢”值)。 然后由於 NaN 趨勢值必須用之前的“趨勢”值填充,我們使用ffill
並用 1 填充剩余的 NaN 值。
import numpy as np
df['Trend'] = (df['Trend'].replace(0, np.nan)
.fillna(pd.Series(np.select([df['Close'] > df['Down'].shift(),
df['Close'] < df['Up'].shift()],
[1, -1], np.nan), index=df.index))
.ffill().fillna(1))
Output:
Close Up Down Trend
0 3.138 NaN NaN 1.0
1 3.141 NaN NaN 1.0
2 3.141 NaN NaN 1.0
3 3.130 NaN NaN 1.0
4 3.110 NaN NaN 1.0
5 3.130 3.026432 3.214568 1.0
6 3.142 3.044721 3.214568 1.0
7 3.140 3.047010 3.214568 1.0
8 3.146 3.059807 3.214568 1.0
9 3.153 3.064479 3.214568 1.0
10 3.173 3.080040 3.214568 1.0
11 3.145 3.080040 3.214568 1.0
12 3.132 3.080040 3.214568 1.0
13 3.131 3.080040 3.209850 1.0
14 3.141 3.080040 3.209850 1.0
15 3.098 3.080040 3.205953 1.0
16 3.070 3.080040 3.195226 -1.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.