【问题标题】:CSV to Specific JSON StructureCSV 到特定 JSON 结构
【发布时间】:2021-11-18 18:10:00
【问题描述】:

在将 CSV 文件转换为 Python 中特定格式的 JSON 文件时,我需要帮助。

我的 CSV 文件如下所示:

Player Name Team R1 Position R1 Price R1 Score R2 Position R2 Price R2 Score
Player A Team A DEF 100000 10 DEF/MID 110000 11
Player B Team B RUC 200000 20 RUC/FWD 210000 21

格式正确的 JSON 文件代码如下:

{
    "Player A": {
        "Team": "Team A",
        "Position": {
            "1": "DEF",
            "2": "DEF/MID"
        },
        "Price": {
            "1": 100000,
            "2": 110000
        },
        "Score": {
            "1": 10,
            "2": 11
        }
    },
    "Player B": {
        "Team": "Team B",
        "Position": {
            "1": "RUC",
            "2": "RUC/FWD"
        },
        "Price": {
            "1": 200000,
            "2": 210000
        },
        "Score": {
            "1": 20,
            "2": 21
        }
    }
}

到目前为止,我当前的 Python 代码包含以下内容,但我坚持从这里到哪里去。我知道我需要将 CSV 的第一行作为标题,并且我需要以某种方式按位置、价格和分数对列进行分组。

import pandas as pd
df = pd.read_csv(r"file_name.csv")
df = df.fillna(0)
df = df.T
df.columns = df.iloc[0]
df = df[1:]
df.to_json(r"file_name.json", orient='columns')

我曾尝试查看和重现许多过去的 Stack Overflow 问题和解决方案,例如: Convert csv to JSON tree structure?

感谢您抽出宝贵时间帮助我!我真的很感激!

【问题讨论】:

  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: python json pandas csv


【解决方案1】:

这里有几个例子。首先没有熊猫,其次是熊猫:-

import json
import pandas as pd
D = {}
FILE = 'players.csv'
with open(FILE) as csv:
    for i, line in enumerate(csv.readlines()):
        if i > 0:
            t = line.strip().split(',')
            k = t[0]
            D[k] = {}
            D[k]['Team'] = t[1].strip()
            D[k]['Position'] = {'1': t[2].strip(), '2': t[5].strip()}
            D[k]['Price'] = {'1': int(t[3]), '2': int(t[6])}
            D[k]['Score'] = {'1': int(t[4]), '2': int(t[7])}
print(json.dumps(D, indent=2))

df = pd.read_csv(FILE)
D = {}
for _, r in df.iterrows():
    k = r['Player Name']
    D[k] = {}
    D[k]['Team'] = r['Team'].strip()
    D[k]['Position'] = {
        '1': r['R1 Position'].strip(), '2': r['R2 Position'].strip()}
    D[k]['Price'] = {'1': r['R1 Price'], '2': r['R2 Price']}
    D[k]['Score'] = {'1': r['R1 Score'], '2': r['R2 Score']}
print(json.dumps(D, indent=2))

【讨论】:

  • 非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 2011-09-21
  • 2019-02-21
  • 2017-04-06
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多