python - 将 Pandas df 转换为字典

标签 python pandas

我需要转换以下格式的 df:

d = {
    'A': ['a1', 'a2', 'a3', 'a4', 'a5'],
    'B': ['b1', 'b2', 'b3', 'b4', 'b5'],
    'C': ['c1', 'c2', 'c3', 'c4', 'c5'],
    'D': ['d1', 'd2', 'd3', 'd4', 'd5'],
    'E': ['e1', 'e2', 'e3', 'e4', 'e5'],
    'F': ['f1', 'f2', 'f3', 'f4', 'f5'],
    'G': ['g1', 'g2', 'g3', 'g4', 'g5'],
    'H': ['h1', 'h2', 'h3', 'h4', 'h5'],
}

df = pd.DataFrame(d)
df
    A   B   C   D   E   F   H
0   a1  b1  c1  d1  g1  f1  h1
1   a2  b2  c2  d2  g2  f2  h2
2   a3  b3  c3  d3  g3  f3  h3
3   a4  b4  c4  d4  g4  f4  h4
4   a5  b5  c5  d5  g5  f5  h5
到以下格式的字典:
out = {
    'a1': {'B':'b1', 'C':'c1', 'D':'d1', 'E':'e1', 'F':'f1', 'G':'g1', 'H':'g1'},
    'a2': {'B':'b2', 'C':'c2', 'D':'d2', 'E':'e2', 'F':'f2', 'G':'g2', 'H':'g2'},
    'a3': {'B':'b3', 'C':'c3', 'D':'d3', 'E':'e3', 'F':'f3', 'G':'g3', 'H':'g3'},
    'a4': {'B':'b4', 'C':'c4', 'D':'d4', 'E':'e4', 'F':'f4', 'G':'g4', 'H':'g4'},
    'a5': {'B':'b5', 'C':'c5', 'D':'d5', 'E':'e5', 'F':'f5', 'G':'g5', 'H':'g5'}
}
有人可以帮忙吗。我试过以下:
df.to_dict(orient='records')

最佳答案

将索引设置为列 A并使用 orient='index' 转换为字典

df.set_index('A').to_dict('index')
输出
{'a1': {'B': 'b1', 'C': 'c1', 'D': 'd1', 'E': 'g1', 'F': 'f1', 'H': 'h1'},
 'a2': {'B': 'b2', 'C': 'c2', 'D': 'd2', 'E': 'g2', 'F': 'f2', 'H': 'h2'},
 'a3': {'B': 'b3', 'C': 'c3', 'D': 'd3', 'E': 'g3', 'F': 'f3', 'H': 'h3'},
 'a4': {'B': 'b4', 'C': 'c4', 'D': 'd4', 'E': 'g4', 'F': 'f4', 'H': 'h4'},
 'a5': {'B': 'b5', 'C': 'c5', 'D': 'd5', 'E': 'g5', 'F': 'f5', 'H': 'h5'}}

关于python - 将 Pandas df 转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69043356/

相关文章:

python - python 如何将函数解释为生成器

python - NumPy 2d 数组的切片,或者如何从 nxn 数组 (n>m) 中提取 mxm 子矩阵?

python - 将多个表从 Pandas read_html() 导出到 csv 文件

python - 如何根据条件过滤 pandas 系列值

python - "ValueError: Length of values does not match length of index"尝试修改 pandas groupby 的列值时

python - Pandas:查找空/缺失值并将其添加到 DataFrame 中

python - 将 s 转换为 h :m in y-axis in matplotlib (data_plot)

Python psycopg2 在 postgresql 表的某些行中插入 NULL

python - 删除 Pandas 中特定列(按名称)之前的所有列?

python - 根据另一列中的值规范化 Pandas 数据框中的列