我正在处理一个用 Pandas 读取的大型 CSV 文件。其中一列(不是索引)是时间戳数据,如下所示:
sent>23:56:51.748912
有前缀 sent>
后跟小时、分钟、秒、微秒。我想修改所有这些时间戳条目,以便时间向后移动 11 小时。所以上面的例子看起来像这样:
sent>12:56:51.748912
我期待/希望有一些足够智能的模算术,以便将 sent>09:02:13.245511
的条目向后移动 11 将变成 sent>22 :02:13.245511
。
我遇到了一些困难,因为 NumPy datetime64
和 Pandas TimeSeries
想要完整的年、月、日,但我没有。到目前为止我看到的文档和示例都相当简洁。我尝试过将数据存储在各种不同的结构中(总结如下),但到目前为止似乎没有任何效果。
(仍在学习 numpy/pandas...请对我放轻松...)这是我尝试过的:
import pandas as pd
import numpy as np
import datetime
df = pd.read_csv(filename, header=None, delimiter=' ', skiprows=2,
skipfooter=2, names=colnames, index_col=False, engine='python')
senttime_col = np.array(df['sent_time'], dtype='str')
senttime_col = np.char.lstrip(senttime_col, 'sent>')
# this creates np array of strings with elements like: 23:56:51.748585
senttimes_ts = pd.to_datetime(df['sent_time'])
# this creates TimeSeries with elements like: sent>23:56:51.748585
senttimes_ts.tshift(pd.Timedelta('-11 hours'))
# ValueError: Freq was not given and was not set in the index
senttimes_df = pd.DataFrame(senttime_col, index=None)
senttimes_df.shift(periods=-11, freq=pd.Timedelta(hours=1))
# TypeError: unsupported operand type(s) for +: 'numpy.int64' and 'Timedelta'
senttimes = np.datetime64(senttime_col)
# ValueError: Could not convert object to NumPy datetime
senttimes = np.datetime64(senttime_col, 'h:m:s.us')
# TypeError: Invalid datetime unit "h:m:s.us" in metadata
senttimes = np.array(senttime_col, dtype='datetime64[us]')
# ValueError: Error parsing datetime string "00:16:51.748269" at position 2
timelist = [datetime.datetime.strptime(x, '%H:%M:%S.%f') for x in senttime_col]
# ValueError: time data 'None' does not match format '%H:%M:%S.%f'
最佳答案
假设,s
是您的系列专栏:
s = pd.Series(['sent>12:56:51.748912'] * 10000)
# this removes the 'sent>' string from the beginning
s = s.str[5:]
我将使用此函数来查找我已经解析的日期 -
def lookup2(s):
'''uses .map() to apply changes'''
dates = {date:pd.to_datetime(date) - pd.Timedelta('11 hours') for date in s.unique()}
return s.map(dates)
然后,我们将结果保存回s
。注意:我没有遇到这个问题 - “我遇到了一些困难,因为 NumPy datetime64 和 Pandas TimeSeries 都需要完整的年、月和日,但我没有这些。”
s = lookup2(s)
In [156]: s.head()
Out[156]:
0 2015-05-10 12:56:51.748912
1 2015-05-10 12:56:51.748912
2 2015-05-10 12:56:51.748912
3 2015-05-10 12:56:51.748912
4 2015-05-10 12:56:51.748912
dtype: datetime64[ns]
将时间拨回 11 小时 -
In [154]: t = (s - pd.Timedelta('11 hours')).dt.time
In [155]: t.head()
Out[155]:
0 23:56:51.748912
1 23:56:51.748912
2 23:56:51.748912
3 23:56:51.748912
4 23:56:51.748912
dtype: object
请告诉我这是否适合您。
关于python - 对不带年、月、日的时间戳数组进行算术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147337/