【问题标题】:Creating a list with data from a Dataframe index in Python在 Python 中使用来自 Dataframe 索引的数据创建列表
【发布时间】:2014-08-25 03:48:48
【问题描述】:

我在尝试将 df 的索引(参见代码)转换为列表时遇到了麻烦,因为当我运行它时,这个列表是一个“时间戳”(我不知道这意味着什么)。代码是

quote='AAPL'
stock = DataReader(quote,'yahoo',start_date,end_date)
stock.head()
df=DataFrame(stock)
xdata = df.index.tolist()

然后当我运行时我得到

[Timestamp('2010-01-04 00:00:00'), Timestamp('2010-01-05 00:00:00'), Timestamp('2010-01-06 00:00:00'), Timestamp('2010-01-07 00:00:00'), Timestamp('2010-01-08 00:00:00')]

但我想要这样的东西:

['2010-01-04', '2010-01-05'), ...,'2010-01-08')]

有人可以帮我解决这个问题吗?

提前致谢!

【问题讨论】:

  • df.index.map(pd.Timestamp.date).tolist()df.index.date.tolist()
  • TimeStamp 是类似于 numpy 的 datetime64 的 pandas dtype,你最好保持索引不变,因为当你想做一些与日期时间相关的操作时,比如找到两个时间戳之间的行或 min/max 如果您转换为字符串,您将无法执行此操作。

标签: python datetime pandas datareader


【解决方案1】:
ts_list = df.index.tolist()  # a list of Timestamp's
date_list = [ ts.date() for ts in ts_list ]  # a list of datetime.date's
date_str_list = [ str(date) for date in date_list ]  # a list of strings

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2020-03-08
    • 1970-01-01
    相关资源
    最近更新 更多