【发布时间】:2020-11-06 08:23:48
【问题描述】:
我有两个数据框
import numpy as np
import pandas as pd
test1 = pd.date_range(start='1/1/2018', end='1/10/2018')
test1 = pd.DataFrame(test1)
test1.rename(columns = {list(test1)[0]: 'time'}, inplace = True)
test2 = pd.date_range(start='1/5/2018', end='1/20/2018')
test2 = pd.DataFrame(test2)
test2.rename(columns = {list(test2)[0]: 'time'}, inplace = True)
现在我在第一个数据框中创建列
test1['values'] = np.zeros(10)
我想填写此列,每个日期旁边应该有与第二个数据框最接近的日期的索引。我希望它看起来像这样:
0 2018-01-01 0
1 2018-01-02 0
2 2018-01-03 0
3 2018-01-04 0
4 2018-01-05 0
5 2018-01-06 1
6 2018-01-07 2
7 2018-01-08 3
当然我的真实数据不是均匀分布的,有分秒,但思路是一样的。我使用以下代码:
def nearest(items, pivot):
return min(items, key=lambda x: abs(x - pivot))
for k in range(10):
a = nearest(test2['time'], test1['time'][k]) ### find nearest timestamp from second dataframe
b = test2.index[test2['time'] == a].tolist()[0] ### identify the index of this timestamp
test1['value'][k] = b ### assign this value to the cell
这段代码在大型数据集上速度很慢,如何提高效率?
附:就像在这些人工示例中一样,我的真实数据中的时间戳被排序和增加。
【问题讨论】:
标签: python pandas sorting datetime