python-3.x - 如何连接列时间值在一定范围内且不是日期时间或时间戳对象的两个数据帧?

标签 python-3.x pandas

我有两个数据框,如下所示:

     time browncarbon blackcarbon
 181.7335    0.105270         NaN
 181.3809    0.166545    0.001217
 181.6197    0.071581         NaN

 422 rows x 3 columns

   start       end    toc 
179.9989  180.0002  155.0
180.0002  180.0016  152.0
180.0016  180.0030  151.0

1364 rows x 3 columns

第一个数据帧有一个时间列,每四分钟有一个瞬间。第二个数据帧有两个时间列,每两分钟间隔一次。这两个时间列不会同时开始和结束。但是,它们包含同一天收集的数据。我怎样才能制作另一个数据框包含:

time browncarbon blackcarbon toc

422 rows X 4 columns

Stack Overflow 上有一个相关的答案,但是,它仅适用于时间列是 datetime 或 timestamp 对象的情况。链接是:How to join two dataframes for which column values are within a certain range?

补充1:封装到其中一个时间行中的多个开始和结束行也应该对应一个目录行,就像现在一样,但是,它应该是多个目录行的平均值,即目前情况并非如此。

附录 2:Merging two pandas dataframes with complex conditions

最佳答案

我们创建一个人工键列来执行外部合并,以取回笛卡尔积(行之间的所有匹配项)。然后我们用 .query 过滤所有时间在范围内的行。

注意:我编辑了一行的值以便我们可以得到一个匹配项(请参阅底部示例数据框中的第 0 行)

df1.assign(key=1).merge(df2.assign(key=1), on='key', how='outer')\
   .query('(time >= start) & (time <= end)')\
   .drop(['key', 'start', 'end'], axis=1)

输出

       time  browncarbon  blackcarbon    toc
1  180.0008      0.10527          NaN  152.0

使用的示例数据框:

df1:

       time  browncarbon  blackcarbon
0  180.0008     0.105270          NaN
1  181.3809     0.166545     0.001217
2  181.6197     0.071581          NaN

df2:

      start       end    toc
0  179.9989  180.0002  155.0
1  180.0002  180.0016  152.0
2  180.0016  180.0030  151.0

关于python-3.x - 如何连接列时间值在一定范围内且不是日期时间或时间戳对象的两个数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57065538/

相关文章:

python - 如何在 python 3 中导入 "HdfsClient"?

python - Python 3.6 及更早版本的精确时间(纳秒)?

python - Pandas - 如何将数据框中的日期范围分割为额外列

python - 增加请求/第二个 Python Google map 地理编码器

python - 模块 'scipy.special' 在 Python/SciPy 中没有 'expit' 成员

python-3.x - 如何在 Mac 上升级 pip?

python - 导入错误 : with error 'is not a package'

python - 总结具有重复列 Pandas 的多行

python - 将多个 DataFrame 列合并为一个

python - 为列中的所有值 reshape 数据框