【问题标题】:Convert row to format matching index将行转换为格式匹配索引
【发布时间】:2020-01-22 10:16:05
【问题描述】:
  1. 我有一个形状为 3000,125 的 df
  2. 我的 df 的第一行代表债券行情
  3. 第二行代表销售日期
  4. 我的指数是历史时间序列,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


    【解决方案1】:

    IIUC,你只是想把第一行变成一个日期时间对象来做一些进一步的操作吗?

    如果是这样,这对我有用 -

    test_ = pd.to_datetime(df.iloc[0].str.replace("*", "").str.replace(".", ""))
    print(test_)
    
    AAPL     2017-04-01
    Google   2021-02-03
    IBM      2020-03-03
    Name: 0, dtype: datetime64[ns]
    

    如果你通过.strftime 方法,你最终会得到一个对象。

    希望对您有所帮助。

    【讨论】:

    • 谢谢。运行上述代码时,我收到以下错误消息:ValueError: value must be an integer, received for year
    • 必须有更多需要替换的项目,您可以在 datetime 中添加一个参数以将异常值强制转换为 NaT pd.to_datetime(date, errors='coerce') 但是我使用了您的数据,它对我有用。
    猜你喜欢
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 2010-10-09
    • 2014-02-09
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多