簡體   English   中英

pandas dataframe 條件人口新列

[英]pandas dataframe conditional population of a new column

我正在處理 pandas DataFrame 中的列(趨勢)。下面是我的源 DataFrame。目前我已將其設置為 0。

在此處輸入圖像描述

我想用來填充趨勢列的邏輯如下

  1. 如果 df['Close'] > df.shift(1)['Down'] 那么 1

  2. 如果 df['Close'] < df.shift(1)['Up'] 那么 -1

  3. 如果上述任何一個條件不滿足,則 df.shift(1)['Trend']。 如果此值為 NaN,則將其設置為 1。

以上純文本代碼,

  1. 如果當前收盤價大於Down列的前一行值,則為 1
  2. 如果當前收盤價小於Up列的前一行值,則 -1
  3. 如果這些條件中的任何一個不滿足,則設置Trend列的前一行值,只要它不是 NaN 如果它的 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.

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