【问题标题】:Timestamp index for pandas dataframe from read_json()来自 read_json() 的 pandas 数据帧的时间戳索引
【发布时间】:2015-12-28 06:55:25
【问题描述】:

我正在从文件 data.json 中读取包含以下内容的单个 JSON 行:

[
  {
    "timestamp": 1436266865,
    "rates": {
      "EUR": 0.911228,
      "JPY": 122.5463,
      "AUD": 1.346118
    }
  },
  {
    "timestamp": 1436277661,
    "rates": {
      "JPY": 122.4789,
      "AUD": 1.348871,
      "EUR": 0.91433
    }
  }
]

放入熊猫数据框。我想使用“时间戳”作为 DataFrame 的索引。我通过以下方式实现:

df = pandas.read_json('data.json')
df.index = df['timestamp']
df.drop('timestamp', axis=1, inplace=1)

是否有可能只用一行来完成?

【问题讨论】:

    标签: python json pandas timestamp


    【解决方案1】:
    import pandas as pd
    
    df = pd.read_json('data.json')
    df.set_index('timestamp',inplace=True)
    print(df)
    

    这会将timestamp 设置为您的索引。 inplace=True 将阻止您必须执行 df=df.set_index('timestamp') 并且默认情况下它会删除该列。

                                                            rates
    timestamp                                                    
    1436266865  {'EUR': 0.9112279999999999, 'JPY': 122.5463, '...
    1436277661  {'JPY': 122.4789, 'AUD': 1.348871, 'EUR': 0.91...
    

    【讨论】:

    • 你指的是哪一行?
    • 为什么这种单线行不通? df = pd.read_json('data.json').set_index('timestamp', inplace=True)
    • 因为dataframe还没有被设置,所以你不能在它上面调用.set_index,除非它已经在内存中执行过了。从右到左读取代码后,代码从左到右完成。因此,为未定义的 DF 调用 .set_index 将导致 None。这能说明问题吗?
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2014-12-09
    • 2014-08-09
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    相关资源
    最近更新 更多