python - 将 Pandas 数据框转换为以第一列为键的字典

标签 python pandas dictionary

我有一个 Pandas 数据框:

A  ||  B  ||  C
x1    x      [x,y]
x2    a      [b,c,d] 
我正在尝试制作一个看起来像这样的字典:
{x1: {B : x, c : [x,y]}, x2: {B: a, C:[b,c,d}}
我试过 to_dict函数,但这会将整个数据框更改为字典。我对如何迭代第一列并使其成为键而将 df 的其余部分设为字典作为该键的值有点迷茫。

最佳答案

尝试:

x = df.set_index("A").to_dict("index")
print(x)
打印:
{'x1': {'B': 'x', 'C': ['x', 'y']}, 'x2': {'B': 'a', 'C': ['b', 'c', 'd']}}

关于python - 将 Pandas 数据框转换为以第一列为键的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68522656/

相关文章:

python - 为什么我的正则表达式也接受字母? ^[0-9\-\+_]

python - 为什么 python dict 的 fromkeys 方法可以接受列表作为参数?

python - 允许 Argparse 参数的特定值

python - 更改一个 df 中的列值以匹配不同 df 中的列值?

python - 为什么 Python 的数值计算速度这么慢?

javascript - 在异步函数内映射数组会导致错误

arrays - 从字典返回类属性的数组

python - Pandas groupby 使用 agg 并同时申请

Python:Pandas 使用公共(public)列合并 2 个数据帧

python - 我怎样才能有效地获得[许多]四分位数?