简体   繁体   English

当对应的值为NaN时,如何根据另一列中的条件从前一行获取一个值?

[英]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.

相关问题 根据条件用数据帧2中的相应值填充数据帧1中的A列中的NaN值 - Populate NaN value in column A of data frame 1 with corresponding value from data frame 2 based on condition 当另一列值与前一行不同时如何处理来自 pct_change 的 NAN 值 - How to deal with NAN values coming from pct_change when another column value is different than previous row 当同一行中的另一列为NaN时,如何从熊猫数据框中选择特定的列值? - How to select a particular column value from a pandas dataframe when another column in the same row is NaN? 用前一行值乘以另一列填充 nan 的熊猫 - pandas filling nan with previous row value multiplied with another column 如何根据另一列填充 nan 值 - how to fill nan value based on another column 如何使用 Pandas 根据同一行中另一列的值替换一列中的 NaN 值? - How to replace NaN value in one column based on the value of another column in the same row using Pandas? Python pandas 根据另一列的条件填充缺失值(NaN) - Python pandas fill missing value (NaN) based on condition of another column Pandas:根据唯一值获取行中对应的列值 - Pandas: Get corresponding column value in row based on unique value 根据行的先前值填充NaN - Fill NaN based on previous value of row 如何根据 NaN 之后的下一个有效值等于前一个有效值的条件回填 NaN 值 - How to backfill NaN values based on condition that next valid value after NaN is equal to previous valid value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM