python - 对齐没有公共(public)索引的 pandas DataFrame

标签 python pandas indexing dataframe

我有代表来自两个不同传感器的数据的数据帧:

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  

传感器为它们正在监视的每个事件提供度量(foobar)和时间戳(time)。有几点需要注意:

  1. 时间戳很接近,但不完全相同
  2. 收集数据的范围因传感器而异(即它们是独立打开和关闭的)

我正在尝试对齐 df0df1 以获得以下内容:

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 开始...

这里是一个起点:

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

关于python - 对齐没有公共(public)索引的 pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39475968/

相关文章:

python - 如何在 Heroku(使用 python)上的 web 和 worker(不同的 dynos)之间通信数据?

python - 在字符串匹配后将行插入文件

python - Django:作为值列表查询一部分的相关模型值列表

python - 使用选定的列表值填充数据框中的列

mysql - 显示/查看数据库 MySQL 中的索引

indexing - 张量的 torch 逻辑索引

python - 跟踪 python : only include some files

python - 了解有关 DataFrame 操作的 Dask 分布式行为

python - 如何从偶数行值中减去奇数行值?

python - 将 3D numpy 数组的切片快速组合为 3D 子数组