我需要向数据帧添加一列,以便第 0 行是 2019 年 2 月 15 日。 第 1 行是第 16 行,依此类推。我尝试使用索引:
import numpy as np
import pandas as pd
df=pd.DataFrame()
df['a']=np.arange(10,20)
df['date from index']=df.apply( lambda x: pd.to_datetime('15-2-2019') + pd.DateOffset(days=x.index), axis=1 )
但我得到:
类型错误: ('必须是 str, not int', '发生在索引 0')
我承认我不明白。 我尝试创建一个显式列来代替索引:
df=pd.DataFrame()
df['a']=np.arange(10,20)
df['counter']=np.arange(0,df.shape[0])
df['date from counter']=df.apply( lambda x: pd.to_datetime('15-2-2019') + pd.DateOffset(days=x['counter']), axis=1 )
但这给了我:
类型错误: ('不支持的时空天数组件类型: numpy.int32', '发生在索引 0')
我做错了什么?
使用to_timedelta
将值转换为天时间增量或使用 参数origin
,使用to_datetime
中的参数unit
指定开始日期:
df['date from index']= pd.to_datetime('15-2-2019') + pd.to_timedelta(df.index, 'd')
df['date from counter']= pd.to_datetime('15-2-2019') + pd.to_timedelta(df['counter'], 'd')
df['date from index1']= pd.to_datetime(df.index, origin='15-02-2019', unit='d')
df['date from counter1']= pd.to_datetime(df['counter'], origin='15-02-2019', unit='d')
print(df.head())
a counter date from index date from counter date from index1
0 10 0 2019-02-15 2019-02-15 2019-02-15
1 11 1 2019-02-16 2019-02-16 2019-02-16
2 12 2 2019-02-17 2019-02-17 2019-02-17
3 13 3 2019-02-18 2019-02-18 2019-02-18
4 14 4 2019-02-19 2019-02-19 2019-02-19
date from counter1
0 2019-02-15
1 2019-02-16
2 2019-02-17
3 2019-02-18
4 2019-02-19
您可以使用pd.to_timedelta
对此进行矢量化:
# pd.to_timedelta(df.index, unit='d') + pd.to_datetime('15-2-2019') # whichever
pd.to_timedelta(df.a, unit='d') + pd.to_datetime('15-2-2019')
0 2019-02-25
1 2019-02-26
2 2019-02-27
3 2019-02-28
4 2019-03-01
5 2019-03-02
6 2019-03-03
7 2019-03-04
8 2019-03-05
9 2019-03-06
Name: a, dtype: datetime64[ns]
df['date_from_counter'] = (
pd.to_timedelta(df.a, unit='d') + pd.to_datetime('15-2-2019'))
df
a counter date_from_counter
0 10 0 2019-02-25
1 11 1 2019-02-26
2 12 2 2019-02-27
3 13 3 2019-02-28
4 14 4 2019-03-01
5 15 5 2019-03-02
6 16 6 2019-03-03
7 17 7 2019-03-04
8 18 8 2019-03-05
9 19 9 2019-03-06
正如预期的那样,您可以使用正确的单位对任何整数列调用pd.to_timedelta
,然后将生成的Timedelta
列用于日期时间算术。
为了使您的代码正常工作,似乎您需要传递int
,而不是np.int
(不知道为什么)。这行得通。
dt = pd.to_datetime('15-2-2019')
df['date from counter'] = df.apply(
lambda x: dt + pd.DateOffset(days=x['counter'].item()), axis=1)
df
a counter date from counter
0 10 0 2019-02-15
1 11 1 2019-02-16
2 12 2 2019-02-17
3 13 3 2019-02-18
4 14 4 2019-02-19
5 15 5 2019-02-20
6 16 6 2019-02-21
7 17 7 2019-02-22
8 18 8 2019-02-23
9 19 9 2019-02-24