[英]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.我正在寻找一种方法来找出 col2 的值,以及当 col1 的值为 1 时的 col3。所以,我正在寻找的输出是 col2:7 和 col3:11。我给出了下面的代码以供参考。 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:您可以ffill
值并以 1 作为值获取第一行的索引:
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:如果您期望有几行值为 1:
d.ffill().loc[d['col1'].eq(1), ['col2', 'col3']]
output:输出:
col2 col3
2015-07-04 7.0 11.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.