简体   繁体   中英

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

I am working with a timeseries data frame. I am looking for a way to find out the value of col2, and col3 when value of col1 is 1. So, the output I am looking for is col2: 7, and col3: 11. I have given the code below for reference. Thanks in advance!

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)

You can ffill the values and get the index of the first row with 1 as value:

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

output:

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

If you expect several rows with value 1:

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

output:

            col2  col3
2015-07-04   7.0  11.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM