Python Pandas – “1D”文件到2D数组
发布时间:2020-12-20 11:42:57 所属栏目:Python 来源:网络整理
导读:我在将嵌套的“2D”字典转换为Pandas DataFrame时看到了 an answer to a question.这将是我的问题的解决方案,但后来我想知道,我是否可以跳过生成嵌套字典的中间步骤.假设我的输入input.txt如下所示: A B 1A C 2B C 3 我可以使用Pandas或Numpy将其转换为以下
我在将嵌套的“2D”字典转换为Pandas DataFrame时看到了
an answer to a question.这将是我的问题的解决方案,但后来我想知道,我是否可以跳过生成嵌套字典的中间步骤.假设我的输入input.txt如下所示:
A B 1 A C 2 B C 3 我可以使用Pandas或Numpy将其转换为以下对称矩阵,而无需生成中间嵌套字典吗? A B C A 0 1 2 B 1 0 3 C 2 3 0 我想避免创建的嵌套字典将是: d = {'A':{'B':1,'C':2},'B':{'C':3}} 我在阅读了“Reading an index with a MultiIndex”上的IO Tools文档后尝试了这个: import pandas as pd df = pd.read_csv('input.txt',sep=' ',index_col=[0,1],header=None) 但是,当我这样做时,我没有获得2D热图: import matplotlib.pyplot as plt plt.pcolor(df) plt.imshow() 解决方法
不确定这是否更有效率,但你可以
pivot ,然后将帧添加到其转置,如:
df = pd.read_csv("input.txt",header=None,delim_whitespace=True) df = df.pivot(0,1,2) df.add(df.T,fill_value=0).fillna(0) A B C A 0 1 2 B 1 0 3 C 2 3 0 这是 0 1 2 0 A B 1 1 A C 2 2 B C 3 然后第二行df = df.pivot(0,2)返回: 1 B C 0 A 1 2 B NaN 3 幻数0,1和2是索引,列和值. index = 0是用于生成新帧索引的列名. index只是一个行名称的pandas lingo. columns = 1是用于生成新帧的列的列名.而values = 2只是用于制作新帧值的列名. 第三行df.add(df.T,fill_value = 0).fillna(0)只是添加转置以将三角矩阵转换为对称矩阵.它返回: A B C A 0 1 2 B 1 0 3 C 2 3 0 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |