使用前
ffill()
np.nan
菲尔()
. 然后将列放回一起,并将该操作包装到
pd.to_datetime
dtype
.
最后,您可以删除时间列。
# Imports
import numpy as np
import pandas as pd
# Split the column
df[['Date','Time']] = df['Date'].str.split(' ',expand=True)
# Replace space with nan and use ffill()
df['Date'] = df['Date'].replace(r'^\s*$', np.nan, regex=True).ffill()
# Put the columns back and convert to datetime
df['Date'] = pd.to_datetime(df['Date'] + ' ' + df['Time'])
# Drop the time column
del(df['Time'])
df
Date Headline
0 2021-03-20 04:03:00 Apple CEO Cook, executives on tentative list o...
1 2021-03-20 03:43:00 Apple CEO Cook, execs on tentative list of wit...
2 2021-03-19 22:19:00 Dow Jones Futures: Why This Market Rally Is So...
3 2021-03-19 18:13:00 Zuckerberg: Apples Privacy Move Could Spur Mor...
4 2021-03-19 17:45:00 Apple (AAPL) Dips More Than Broader Markets: W...
5 2021-03-19 16:17:00 Facebook Stock Jumps As Zuckerberg Changes Tun...
6 2021-03-19 16:03:00 Best Dow Jones Stocks To Buy And Watch In Marc...
7 2021-03-19 13:02:00 The Nasdaq's on the Rise Friday, and These 2 S...
编辑
如果你想让你的“日期”在你想要的结果中准确地显示出来,也就是说,这个格式是“Mar-20-21”,不要把它包装起来
pd.to_datetime()
object
:
df['Date'] = df['Date'] + ' ' + df['Time']
df
Date Headline
0 Mar-20-21 04:03AM Apple CEO Cook, executives on tentative list o...
1 Mar-20-21 03:43AM Apple CEO Cook, execs on tentative list of wit...
2 Mar-19-21 10:19PM Dow Jones Futures: Why This Market Rally Is So...
3 Mar-19-21 06:13PM Zuckerberg: Apples Privacy Move Could Spur Mor...
4 Mar-19-21 05:45PM Apple (AAPL) Dips More Than Broader Markets: W...
5 Mar-19-21 04:17PM Facebook Stock Jumps As Zuckerberg Changes Tun...
6 Mar-19-21 04:03PM Best Dow Jones Stocks To Buy And Watch In Marc...
7 Mar-19-21 01:02PM The Nasdaq's on the Rise Friday, and These 2 S...