当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Aligning pandas DataFrames that don't have a common index

问题描述:

I have DataFrames that represent data from two different sensors:

In[0]: df0

Out[0]:

time foo

0 0.1 123

1 1.0 234

2 2.1 345

3 3.1 456

4 3.9 567

5 5.1 678

In[0]: df1

Out[0]:

time bar

0 -0.9 876

1 -0.1 765

2 0.7 654

3 2.1 543

4 3.0 432

The sensors provide a measure (foo or bar) and a timestamp (time) for each events that they are monitoring. A couple things to note:

  1. the timestamps are close, but not identical
  2. the range over which data was collected is different across sensors (i.e. they were turned on and turned off independently)

I'm trying to align df0 and df1 to get the following:

In[3]: df3

Out[3]:

time_df0 foo time_df1 bar

0 nan nan -0.9 876

1 0.1 123 -0.1 765

2 1.0 234 0.7 654

3 2.1 345 2.1 543

4 3.1 456 3.0 432

5 3.9 567 nan nan

6 5.1 678 nan nan

网友答案:

@Kartik posted a perfect links to start with...

Here is a starting point:

df0.set_index('time', inplace=True)
df1.set_index('time', inplace=True)

In [36]: df1.reindex(df0.index, method='nearest').join(df0)
Out[36]:
      bar  foo
time
0.1   765  123
1.0   654  234
2.1   543  345
3.1   432  456
3.9   432  567
5.1   432  678
分享给朋友:
您可能感兴趣的文章:
随机阅读: