【问题标题】:Converting a DataFrame into JSON-list using Python3使用 Python3 将 DataFrame 转换为 JSON 列表
【发布时间】:2020-11-10 03:42:03
【问题描述】:

这是我从将 pandas 数据帧转换为我想要的格式所取得的进展。

print(data_frame)

Output:

>>{'Country': ['Croatia', 'Serbia', 'United States', 'Algeria', 'Chile'],
 'Value': [5, 5, 4, 2, 2]}

dictlist = []

for key, value in data_frame.items():
    temp = [key,value]
    dictlist.append(temp)
    
print(dictlist)

Output:

>>[['Country', ['Croatia', 'Serbia', 'United States', 'Algeria', 'Chile']], ['Value', [5, 5, 4, 2, 2]]]

现在我迷路了。我尝试了很多视频和教程的组合,以至于我的蛮力想法都是空的。

for key, val in dictlist:
    print(key, "->", val)
    for item in val:
        print(item)
   
output:

>>Country -> ['Croatia', 'Serbia', 'United States', 'Algeria', 'Chile']
>>Croatia
>>Serbia
>>United States
>>Algeria
>>Chile
>>Value -> [5, 5, 4, 2, 2]
>>5
>>5
>>4
>>2
>>2

我只是不知道如何在那个 for 循环中工作。我不能再重复了。 这是我试图将其转换为的格式:

[
  {
    "name": "Croatia",
    "value": 5,
  },
  {
    "name": "Serbia",
    "value": 5,
  },
  {
    "name": "United States",
    "value": 4,
  },
  {
    "name": "Algeria",
    "value": 2,
  },
  {
    "name": "Chile",
    "value": 2,
  }
]

更新

感谢聊天中的友好伙伴,我现在离目标更近了。这条线对我帮助很大。

data_frame = frame.set_index('Country').T.to_dict('list')
print(data_frame)

output:

{'Croatia': [5],
 'Serbia': [5],
 'United States': [4],
 'Algeria': [2],
 'Chile': [2]}

Not sure why the values got converted into arrays, but at least this should be solvable! Cheers!

【问题讨论】:

标签: json python-3.x pandas list dictionary


【解决方案1】:

这将根据问题返回字典。

# this is the data frame 
frame = pd.DataFrame({'Country': ['Croatia', 'Serbia', 'United States', 'Algeria', 'Chile'],

查看 to_dict 的 pandas 文档,以获取除已发布代码示例中使用的“列表”之外的可用参数选项。

现在可以满足于在列表中返回字典的“记录”:

data_frame = frame.set_index('Country')T.to_dict('records')[0]

# this is the output without [0]
# [{'Croatia': 5, 'Serbia': 5, 'United States': 4, 'Algeria': 2, 'Chile': 2}]
# so you need the [0] to pick the dictionary in the list and get the desired dictionary output.

【讨论】:

    猜你喜欢
    • 2019-05-19
    • 1970-01-01
    • 2022-01-07
    • 2018-07-13
    • 2021-11-21
    • 2017-06-04
    • 2021-07-09
    • 1970-01-01
    • 2017-04-13
    相关资源
    最近更新 更多