簡體   English   中英

當對應的值為NaN時,如何根據另一列中的條件從前一行獲取一個值?

[英]How to get a value from a previous row when the corresponding value is NaN based on a condition in another column?

我正在使用時間序列數據框。 我正在尋找一種方法來找出 col2 的值,以及當 col1 的值為 1 時的 col3。所以,我正在尋找的輸出是 col2:7 和 col3:11。我給出了下面的代碼以供參考。 提前致謝!

d = {'col1': [0,0,1,0,0], 'col2' : [0,7,'N/A',9,10], 'col3': [11,'N/A','N/A',14,15]}
index = pd.DatetimeIndex(['2014-07-04', '2014-08-04', '2015-07-04', '2015-08-04', '2015-09-04'])
d = pd.DataFrame(data = d, index = index)
d = d.replace('N/A', np.nan)

您可以ffill值並以 1 作為值獲取第一行的索引:

d.ffill().loc[d['col1'].eq(1).idxmax(), ['col2', 'col3']]

輸出:

col2     7.0
col3    11.0
Name: 2015-07-04 00:00:00, dtype: float64

如果您期望有幾行值為 1:

d.ffill().loc[d['col1'].eq(1), ['col2', 'col3']]

輸出:

            col2  col3
2015-07-04   7.0  11.0

暫無
暫無

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

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