gpt4 book ai didi

Python Pandas : how to create a column which is a fixed date + the # days in another column

转载 作者:行者123 更新时间:2023-11-28 21:33:11 26 4
gpt4 key购买 nike

我需要向数据框中添加一列,以便第 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 )

但我得到:

TypeError: ('must be str, not int', 'occurred at index 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 )

但这给了我:

TypeError: ('unsupported type for timedelta days component: numpy.int32', 'occurred at index 0')

我做错了什么?

最佳答案

使用to_timedelta用于将值转换为日时间增量或使用参数origin,指定开始日期,参数unit位于to_datetime :

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

关于Python Pandas : how to create a column which is a fixed date + the # days in another column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55000380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com