【问题标题】:Read date format DD/MM/YYYY using pandas.read_json使用 pandas.read_json 读取日期格式 DD/MM/YYYY
【发布时间】:2022-01-13 08:50:32
【问题描述】:

我有一个日期格式为 DD/MM/YYYY 的文件 date.json

{
    "18/3/2020": 0,
    "19/3/2020": 3,
    "20/3/2020": 5,
    "21/3/2020": 1,
    "22/3/2020": 6,
    "23/3/2020": 3,
    ...
    "11/1/2022": 558,
    "12/1/2022": 0
}

我使用以下代码读取json文件

series = pd.read_json("date.json", typ="series")
df = pd.DataFrame({'date':series.index, column:series.values}).set_index("date")

但是当我尝试打印日期列时,日期数据保存为 YYYY-MM-DD 并误认为 2022 年 1 月 12 日是 2022 年 12 月 1 日如下

date                                                                 
2020-03-18                         
2020-03-19                        
2020-03-20                            
2020-03-21                           
2020-03-22                          
...                           
2022-08-01                           
2022-09-01                       
2022-10-01                         
2022-11-01                         
2022-12-01

什么可以在不更改数据文件的情况下以正确的日期格式读取 json 数据?

【问题讨论】:

  • 你的代码有什么问题?
  • 我通过pd.read_json将一个json文件读入dataframe,但它误解了2022年1月12日(12/1/2022)是2022年12月1日(2022-12-01)
  • 在您的预期输出中,应该是 2022-12-01(已经是 2022 年 12 月 1 日)或 2022-01-12(2022 年 1 月 12 日)
  • 应该是2022-01-12
  • 好的。但你的数据不可能......因为“18/3/2020”不能是“2020-18-3”

标签: python pandas date


【解决方案1】:

您可以通过在 pandas 中指定日期格式来做到这一点。 请记住,默认情况下,pandas 会将日期显示为年-月-日。

df.index=pd.to_datetime(df.index,format='%d/%m/%Y')

#output:
            value
2020-03-18      0
2020-03-19      3
2020-03-20      5
2020-03-21      1
2020-03-22      6
2020-03-23      3
2022-01-11    558
2022-01-12      0

如果您想验证月份和日期的读取是否正确,您可以创建包含日期和月份编号的列。请注意,它读取的最后一行是 1 月 12 日

df.index=pd.to_datetime(df.index,format='%d/%m/%Y')
df['dates_str']=df.index.map(lambda x: x.strftime('%b %d %Y'))
df['day']=df.index.day
df['month']=df.index.month
df['year']=df.index.year

#output
            value    dates_str  day  month  year
2020-03-18      0  Mar 18 2020   18      3  2020
2020-03-19      3  Mar 19 2020   19      3  2020
2020-03-20      5  Mar 20 2020   20      3  2020
2020-03-21      1  Mar 21 2020   21      3  2020
2020-03-22      6  Mar 22 2020   22      3  2020
2020-03-23      3  Mar 23 2020   23      3  2020
2022-01-11    558  Jan 11 2022   11      1  2022
2022-01-12      0  Jan 12 2022   12      1  2022

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2015-03-22
    相关资源
    最近更新 更多