【问题标题】:Python Pandas convert grouped result to a new list and JSONPython Pandas 将 groupby 结果转换为新列表和 JSON
【发布时间】:2020-09-10 14:27:52
【问题描述】:

我是 Python 和 Pandas 的新手,我正在尝试从 JSON 文件中获取和解析数据,并将数据转换为新的列表和 JSON 文件。

这是我用来获取值的代码。

def groupDataByPanda():
    file = open('/Users/bryce/Desktop/Dengue_Daily_10.json', 'r', encoding='utf-8')
    df = pd.read_json(file)
    date_group = df.groupby(['date'])
    df = date_city_group = date_group['city'].value_counts()

    print(df)
    df.to_json(r'Result.json', orient='records')

当我 print(df) 时值是正确的,但是当我尝试 df.values.tolist() 时,它变成了 [2, 2, 1, 1...] 的列表,没有任何日期和城市名称.

如何将 df 转换为这样的列表并写入新的 JOSN 文件。

JSON 文件:

 [{"date":"1998/01/02","case_study":"None","notice_date":"1998/01/07","gender":"m","age":"40-44","city":"London","vell":"None","min_area":"A1320-0136-00","min_X":"120.505898941","min_Y":"22.464206650","unit_area":"A1320-04-008","second_code":"A1320-04","inflict_city":"None","inflict_town":"None","inv":"None","outsider":"no","inflict_country":"None","scode":"1"},
...
]

【问题讨论】:

  • 请粘贴到`/Users/bryce/Desktop/Dengue_Daily_10.json'
  • 请检查您的路径。
  • @KritiPawar 路径正确,我可以读取和处理 JSON 文件中的数据。但我无法将结果转换为格式正确的列表。

标签: python json pandas list


【解决方案1】:

你可以试试这个:-

from collections import Counter
def count_city(x):
    return dict(Counter(x))

def groupDataByPanda():
    file = open('/Users/bryce/Desktop/Dengue_Daily_10.json', 'r', encoding='utf-8')
    df = pd.read_json(file)
    res = df.groupby('date').agg({
        'city': [('count', count_city)],
    })
    res.columns = res.columns.droplevel()
    res.reset_index(inplace=True) 
    data = res.to_dict(orient="records")
    final_json = [dict({"date":x["date"]},**x["count"]) for x in data]
    print(final_json)

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2016-06-07
    • 2021-05-24
    • 1970-01-01
    • 2017-01-12
    • 2022-12-01
    • 2013-07-14
    • 2018-02-04
    • 2021-09-27
    • 2021-11-14
    相关资源
    最近更新 更多