Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 日期范围在两列之间_Python_Pandas_Numpy_Data Manipulation - Fatal编程技术网

Python 日期范围在两列之间

Python 日期范围在两列之间,python,pandas,numpy,data-manipulation,Python,Pandas,Numpy,Data Manipulation,我是Python和数据科学的新手 我有一个数据集,有两个日期时间列a和B: A B 0 2019-03-13 08:12:20 2019-03-13 08:12:25 1 2019-03-15 10:02:18 2019-03-13 10:02:20 对于每一行,我想在列A和列B之间生成以秒为单位的日期范围,因此我应该得到以下结果: A 0 2019-03-13 08

我是Python和数据科学的新手

我有一个数据集,有两个日期时间列
a
B

                     A                    B
0  2019-03-13 08:12:20  2019-03-13 08:12:25
1  2019-03-15 10:02:18  2019-03-13 10:02:20
对于每一行,我想在列A和列B之间生成以秒为单位的日期范围,因此我应该得到以下结果:

                    A
0 2019-03-13 08:12:20
1 2019-03-13 08:12:21
2 2019-03-13 08:12:22
3 2019-03-13 08:12:23
4 2019-03-13 08:12:24
5 2019-03-13 08:12:25
我用这个做的:

import pandas as pd, numpy as np

df=pd.DataFrame({'A': ["2019-03-13 08:12:20", "2019-03-15 10:02:18"], 'B': ["2019-03-13 08:12:25", "2019-03-13 10:02:20"]})
l=[pd.date_range(start=df.iloc[i]['A'], end=df.iloc[i]['B'], freq='S') for i in range(len(df))]
df1=(pd.DataFrame(l).T)[0]
print(df1)

但由于我有大约1百万行,运行时间太长,我知道这个解决方案并不是最好的,你们能告诉我什么是最好的方法吗?

这里是必要的循环,一个可能的解决方案,可以理解列表并将其展平:

l = [x for a, b in zip(df.A, df.B) for x in pd.date_range(a, b, freq='S')]
df1= pd.DataFrame({'A':l})
print(df1)
                    A
0 2019-03-13 08:12:20
1 2019-03-13 08:12:21
2 2019-03-13 08:12:22
3 2019-03-13 08:12:23
4 2019-03-13 08:12:24
5 2019-03-13 08:12:25
另一个解决方案:

df1 = (pd.concat([pd.Series(pd.date_range(r.A, r.B, freq='S')) for r in df.itertuples()])
         .to_frame('A'))
print (df1)
                    A
0 2019-03-13 08:12:20
1 2019-03-13 08:12:21
2 2019-03-13 08:12:22
3 2019-03-13 08:12:23
4 2019-03-13 08:12:24
5 2019-03-13 08:12:25

df.apply(lambda row:list(pd.date_range(row['A'],end=row['B'],freq='S')),axis=1)。explode()
我有一个大约1M行的数据集,我不认为apply可以完成工作x)有没有其他方法在没有循环的情况下实现这一点?是的,
apply
仍然是引擎盖下的循环,因此不可用,也许在numpy中存在一些更好的解决方案。你能告诉我使用numpy的正确方法吗?