【发布时间】:2020-01-22 10:16:05
【问题描述】:
- 我有一个形状为 3000,125 的 df
- 我的 df 的第一行代表债券行情
- 第二行代表销售日期
-
我的指数是历史时间序列,df中的数值代表每日股价 例如
AAPL GOOGLE IBM 16/02/2018 15/03/2022 22/08/2020 2019/jan/02 5 4 3 2019/jan/03. 4 4 4 2019/jan/04. 4 4 5 2019/jan/05 3 5 2 2012/Mar/03 10 20 22
我想对这些值运行一个循环,但是要这样做,索引和df.iloc[0] aka 第一行需要采用相同的格式。
我能够使用以下没有问题的代码将索引转换为日期时间格式:
dftest2.index = pd.to_datetime(dftest2.index, format='%Y%m%d')
问题陈述是我想转换 df 的第一行以匹配索引格式。第一行是'%d/%m/Y%') 形式的字符串格式,但是为了匹配它需要在'%Y%m%d' 中的索引。
为了匹配索引的日期格式,我使用了以下代码:
dftest2.iloc[0] = pd.to_datetime(dftest2.iloc[0]).dt.strftime('%Y-%m-%d')
运行以下代码也会产生以下错误:
dftest2.iloc[0] = pd.to_datetime(dftest2.iloc[0]).datetime.strptime('%Y-%m-%d')
AttributeError: 'Series' object has no attribute 'datetime'
坚持现在如何将其转换为日期时间格式匹配索引。以前转换为日期时间的尝试导致该行被转换为带有无意义数字的 int 格式,例如 187745300000 等。
如何转换行以匹配索引。我现在运行循环时遇到的错误是:
TypeError: '>' not supported between instances of 'numpy.ndarray' and 'str'
我已经在 stackoverflow 上查看了我的问题的可能变化,但没有成功。
【问题讨论】:
标签: python pandas loops datetime