python - 来自 df 的字典,键内有列

标签 python dataframe dictionary

我有一个如下所示的 df:

data = [['a', 10, 1], ['b', 15,12], ['c', 14,12]] 
df = pd.DataFrame(data, columns = ['Name', 'x', 'y'])

  Name   x   y
0    a  10   1
1    b  15  12
2    c  14  12

现在我希望它将它传递给一个字典,其中 xy 位于名为 total 的键内: 所以最终的字典会是这样的

{
'Name': 'a',
"total": {
            "x": 308,
            "y": 229
        },
}

我知道我可以使用df.to_dict('records')来获取这个字典:

{
'Name': 'a',
"x": 308,
"y": 229
}

有什么建议吗?

最佳答案

你可以试试

my_dict = [{'Name': row['Name'], 'total': {'x': row['x'], 'y': row['y']}} for row in df.to_dict('records')]

结果:

[{'Name': 'a', 'total': {'x': 10, 'y': 1}}, {'Name': 'b', 'total': {'x': 15, 'y': 12}}, {'Name': 'c', 'total': {'x': 14, 'y': 12}}]

或者,如果您希望将除“名称”之外的所有列转换为“总计”,并且前提是“名称”中没有重复:

df.set_index('Name', inplace=True)
result = [{'Name': name, 'total': total} for name, total in df.to_dict('index').items()]

结果与之前相同。

关于python - 来自 df 的字典,键内有列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59893415/

相关文章:

python - 在 Google 翻译中使用 BeautifulSoup4

python - 将字符转换为数据框中的数值

dictionary - 如何在不知道键的情况下从 F# Map 获取第一个键值对?

Python 元组访问问题?

python - 终止在另一个 if 条件中的 if 条件中创建的进程

javascript - Python - 使用请求模块重建 Javascript 生成的代码

c++ - 在 win7-64 位中通过 mingw 使用 boost.python 编译一些代码

python - 在 Pandas 数据框中用可变类型替换 NaN

python - 导出 pandas DataFrame 时如何删除列名行?

python - 将键的所有其他值设置为0(第一个值除外)的Python方法