从数据框中的列日期中减去时间间隔 Pandas Python
subtracting time intervals from column dates in dataframes Pandas Python
如何从 data['date']
列中减去 1 秒 1 分钟和 1 个月?
import pandas as pd
d = {'col1': [4, 5, 2, 2, 3, 5, 1, 1, 6], 'col2': [6, 2, 1, 7, 3, 5, 3, 3, 9],
'label':['Old','Old','Old','Old','Old','Old','Old','Old','Old'],
'date': ['2022-01-24 10:07:02', '2022-01-27 01:55:03', '2022-01-30 19:09:03', '2022-02-02 14:34:06',
'2022-02-08 12:37:03', '2022-02-10 03:07:02', '2022-02-10 14:02:03', '2022-02-11 00:32:25',
'2022-02-12 21:42:03']}
data = pd.DataFrame(d)
# subtract the dates by 1 second
date_mod_s = pd.to_datetime(data['date'])
# subtract the dates by 1 minute
date_mod_m = pd.to_datetime(data['date'])
# subtract the dates by 1 month
date_mod_M = pd.to_datetime(data['date'])
您的 date
列是字符串类型。将其转换为 pd.Timestamp
,您可以使用 pd.DateOffset
:
pd.to_datetime(data["date"]) - pd.DateOffset(months=1, minutes=1, seconds=1)
如何从 data['date']
列中减去 1 秒 1 分钟和 1 个月?
import pandas as pd
d = {'col1': [4, 5, 2, 2, 3, 5, 1, 1, 6], 'col2': [6, 2, 1, 7, 3, 5, 3, 3, 9],
'label':['Old','Old','Old','Old','Old','Old','Old','Old','Old'],
'date': ['2022-01-24 10:07:02', '2022-01-27 01:55:03', '2022-01-30 19:09:03', '2022-02-02 14:34:06',
'2022-02-08 12:37:03', '2022-02-10 03:07:02', '2022-02-10 14:02:03', '2022-02-11 00:32:25',
'2022-02-12 21:42:03']}
data = pd.DataFrame(d)
# subtract the dates by 1 second
date_mod_s = pd.to_datetime(data['date'])
# subtract the dates by 1 minute
date_mod_m = pd.to_datetime(data['date'])
# subtract the dates by 1 month
date_mod_M = pd.to_datetime(data['date'])
您的 date
列是字符串类型。将其转换为 pd.Timestamp
,您可以使用 pd.DateOffset
:
pd.to_datetime(data["date"]) - pd.DateOffset(months=1, minutes=1, seconds=1)