[英]Populate NaN value in column A of data frame 1 with corresponding value from data frame 2 based on condition
[英]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.