我正在尝试比较两个DataFrame,我希望有效地使用pandas (or numpy)
而不是带有if语句的嵌套for循环来解决特定问题。下面是我程序的一个小片段。
和value,以获得df2中newtimestart和newtimeend之间的对应值。 。下面是代码。spindleload = {'time': ['2020-02-03 00:18:07', '2020-02-03 00:18:08', '2020-02-03 00:18:09', '2020-02-03 00:18:10', '2020-02-03 00:18:11', '2020-02-03 00:18:12', '2020-02-03 00:18:13', '2020-02-03 00:18:14', '2020-02-03 00:18:15', '2020-02-03 00:18:16', '2020-02-03 00:18:17'], 'value': [17,25,14,14,22,22,22,22,22,12,19]} df1 = pd.DataFrame(data=spindleload) cycletime = {'newtimestart': ['2020-02-03 00:18:08','2020-02-03 00:18:13'], 'newtimeend': ['2020-02-03 00:18:11', '2020-02-03 00:18:15']} df2 = pd.DataFrame(data=cycletime)
现在,我希望循环获取df1]中的time
方法解决此问题。output_graph_time = [] output_graph_value = [] for i in range(len(df2)): for j in range(len(df1)): if df1['time'][j] >= df2['newtimestart'][i]: output_graph_time.append(df1['time'][j]) output_graph_value.append(df1['value'][j]) if df1['time'][j] == df2['newtimeend'][i]: break print(output_graph_time) print(output_graph_value)
现在,代码可以正常工作,但是当它读取数百万行数据时,它无法执行,我也尝试实现
或Pandas vectorizationNumba
,但是内核无法处理,并且无法重新启动。因此,我要求使用Numpy
此外,当我尝试使用向量化方法时,发现在每次执行后如果出现条件则很难打破。
我正在尝试比较两个DataFrame,我希望有效地使用pandas(或numpy),而不是使用带if语句的嵌套for循环来解决特定问题。以下是我的小片段...
您可以在日期范围内转换df2并爆炸,然后使用isin
过滤器df1。
从字符串转换为日期时间:
我知道df1
是几百万行。如果df2
不太大,则可以进行交叉合并: