Python:如何创建固定日期的列+;另一栏中的#天
我需要向数据帧添加一列,以便第0行是2019年2月15日。第1行是第16行,等等。我尝试使用索引:Python:如何创建固定日期的列+;另一栏中的#天,python,pandas,date,Python,Pandas,Date,我需要向数据帧添加一列,以便第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 ) df=pd.D
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 )
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 )
但我得到:
TypeError:(“必须是str,而不是int”,“发生在索引0上”)
我承认我不明白。
我尝试创建一个显式列来代替索引:
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 )
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 )
但这给了我:
TypeError:('timedelta days组件不支持的类型:
numpy.int32','发生在索引0')
我做错了什么?您可以使用
pd将其矢量化。到\u 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]
正如预期的那样,您可以调用
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
用于将值转换为日时间增量或使用
参数origin
带有参数unit
指定开始日期,位于:
谢谢你们两位!就为了我的理解,我在我的例子中做错了什么?编辑了我的答案