根据来自另一个数据框的行范围添加/填充熊猫列

使用熊猫,我已经按时间样本对df1进行了索引:


data = '''\

time       flags    input                  

8228835.0  53153.0  32768.0

8228837.0  53153.0  32768.0

8228839.0  53153.0  32768.0

8228841.0  53153.0  32768.0

8228843.0  61345.0  32768.0'''


fileobj = pd.compat.StringIO(data)

df1 = pd.read_csv(fileobj, sep='\s+', index_col='time')

df2以开始和结束指示时间范围,以定义“ check”状态为True的范围:


data = '''\

        check     start       end

20536   True   8228837   8228993

20576   True   8232747   8232869

20554   True   8230621   8230761

20520   True   8227351   8227507

20480   True   8223549   8223669

20471   True   8221391   8221553'''


fileobj = pd.compat.StringIO(data)

df2 = pd.read_csv(fileobj, sep='\s+')

我需要做的是在df1中添加一列“检查”,并用True值填充df2中定义的实际时间范围。所有其他人都应该是错误的。一个示例结果将是:


             flags    input    check

time                       

8228835.0  53153.0  32768.0    False

8228837.0  53153.0  32768.0    True

8228839.0  53153.0  32768.0    True

8228841.0  53153.0  32768.0    True

8228843.0  61345.0  32768.0    True

....

8228994.0. 12424.0. 32768.0.   False


陪伴而非守候
浏览 144回答 3
3回答

回首忆惘然

您可以创建一个列表或范围,然后pd.Index.isin与使用itertools.chain:from itertools import chaindf2 = df2[df2['check']]ranges = map(range, df2['start'], df2['end'])df1['check'] = df1.index.isin(chain.from_iterable(ranges))print(df1)             flags    input  checktime                              8228835.0  53153.0  32768.0  False8228837.0  53153.0  32768.0   True8228839.0  53153.0  32768.0   True8228841.0  53153.0  32768.0   True8228843.0  61345.0  32768.0   True

倚天杖

我想你可以使用IntervalIndex与locdf2.index=pd.IntervalIndex.from_arrays(df2.start,df2.end,'both')df2.loc[df.index]Out[174]:         check  start  end[1, 2]   True      1    2[4, 5]   True      4    5[7, 8]   True      7    8df['newcol']=df2.loc[df.index].check.values.tolist()dfOut[176]:        flags    input  newcolflags                        2          2  32768.0    True4          4  32768.0    True7          7  32768.0    True

幕布斯6054654

使用的列表理解any()。但是,如果您可以为我们运行%timing,那么对实际性能没有任何了解,那就太好了!df1['check'] = [any(start <= i <= end for start,end in&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; zip(df2['start'], df2['end'])) for i in df1.index]print(df1)返回值:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;flags&nbsp; &nbsp; input&nbsp; checktime&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;8228835.0&nbsp; 53153.0&nbsp; 32768.0&nbsp; False8228837.0&nbsp; 53153.0&nbsp; 32768.0&nbsp; &nbsp;True8228839.0&nbsp; 53153.0&nbsp; 32768.0&nbsp; &nbsp;True8228841.0&nbsp; 53153.0&nbsp; 32768.0&nbsp; &nbsp;True8228843.0&nbsp; 61345.0&nbsp; 32768.0&nbsp; &nbsp;True
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python