Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将简单的网络数据帧更改为关联表?_Python_Pandas_Dataframe - Fatal编程技术网

Python 如何将简单的网络数据帧更改为关联表?

Python 如何将简单的网络数据帧更改为关联表?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个这种格式的数据帧 from to weight 0 A D 3 1 B A 5 2 C E 6 3 A C 2 我希望将其转换为如下所示的相关类型数据帧- A B C D E A 0 0 2 0 3 B 5 0 0 0 0 C 0 0 0 0 6 D 0 0 0 0 0 E 0 0 0 0 0 我认为一个可能的(读起来很幼稚)解决方案是在数据帧上循环,然后通过比较行和列将值分配给另一个数据帧的正确单元格 类似于此: new_df = pd.Da

我有一个这种格式的数据帧

  from to weight
0    A  D 3
1    B  A 5
2    C  E 6
3    A  C 2
我希望将其转换为如下所示的相关类型数据帧-

  A B C D E
A 0 0 2 0 3
B 5 0 0 0 0
C 0 0 0 0 6
D 0 0 0 0 0
E 0 0 0 0 0
我认为一个可能的(读起来很幼稚)解决方案是在数据帧上循环,然后通过比较行和列将值分配给另一个数据帧的正确单元格

类似于此:

new_df = pd.DataFrame(columns = sorted(set(df["from"])), index =sorted(set(df["from"])))

for i in range(len(df)):
    cor.loc[df.iloc[i,0], df.iloc[i,1]] = df.iloc[i,2]
这起作用了。然而,我读过关于不在数据帧上循环的文章


主要的问题是我的数据帧比这个大——几千行。所以我想知道是否有其他的解决方法,因为这个方法不适合我,因为它是Pythonic。也可能更快,因为速度是一个问题。

IIUC,这是一个带有reindex的枢轴:

(df.pivot(index='from', columns='to', values='weight')
 .reindex(all_vals)
 .reindex(all_vals,axis=1)
 .fillna(0)
)
输出:

to      A    B    C    D    E
from                         
A     0.0  0.0  2.0  3.0  0.0
B     5.0  0.0  0.0  0.0  0.0
C     0.0  0.0  0.0  0.0  6.0
D     0.0  0.0  0.0  0.0  0.0
E     0.0  0.0  0.0  0.0  0.0

谢谢你的回答。这里的
all\u vals
是什么?
df.pivot('from','to','weight')。fillna(0)
也应该这样做,只保留最后的值。@Abhishek
all\u vals=['A','B','C','D','E']
这样你就可以拥有所有的列/行。@filippo
df['from','to'].stack().unique()
或者只使用
np unique(df['from','to'])
用于性能测试