使用字典创建DataFrame:将特定结构字典转为指定格式DataFrame
实现方法
步骤说明
给定字典的键是两位数字拼接而成(比如1011对应行10、列11),目标是构建一个对称DataFrame:对角线值设为1,非对角线值按字典填充且矩阵对称。
代码实现
import pandas as pd inpt = {1011: .12, 1012: .43, 1013: .33, 1014: .54, 1112: .4, 1113: .32, 1114: .76, 1213: .54, 1214: .544, 1314: .44, } # 1. 提取所有唯一的行/列索引 indices = set() for key in inpt.keys(): row = int(str(key)[:2]) col = int(str(key)[2:]) indices.add(row) indices.add(col) sorted_indices = sorted(indices) # 2. 创建空DataFrame并初始化对角线为1 df = pd.DataFrame(index=sorted_indices, columns=sorted_indices).fillna(0) for idx in sorted_indices: df.loc[idx, idx] = 1 # 3. 填充字典值并保证矩阵对称 for key, val in inpt.items(): row = int(str(key)[:2]) col = int(str(key)[2:]) df.loc[row, col] = val df.loc[col, row] = val # 4. 调整显示格式(保留两位小数) df = df.round(2) print(df.to_string())
输出结果
运行后得到与示例格式一致的DataFrame:
10 11 12 13 14 10 1.00 0.12 0.43 0.33 0.54 11 0.12 1.00 0.40 0.32 0.76 12 0.43 0.40 1.00 0.54 0.54 13 0.33 0.32 0.54 1.00 0.44 14 0.54 0.76 0.54 0.44 1.00
注:示例中的.01和01应为输入笔误,这里统一将对角线设为1.00,若需自定义对角线值,修改步骤2的赋值即可。
内容的提问来源于stack exchange,提问作者Maukthik Srivathsan J
相关产品推荐
相关产品推荐

