从数据帧转换到矩阵是否有可能? [英] Is it possible from dataframe transform to Matrix?

查看:102
本文介绍了从数据帧转换到矩阵是否有可能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手, 我有一个很大的dataframe:

I am newbie in python, I have a huge dataframe:

Person  OD
A       BS1
A       BS2
B       BS4
B       BS8
C       BS5
C       BS1
D       BS9
D       BS7
E       BS2
E       BS7
F       BS2
F       BS1
G       BS1
G       BS2

是否有可能转换成python-pandas中的原点(OD)矩阵?例如,从BS1到BS2有2个人(A和G),然后在OD矩阵中有2个人进入BS1-BS2.

is it possible to transform into an origin-destination (OD) matrix in python-pandas? Example from BS1 to BS2 there is 2 person (A and G) then in OD matrix 2 people into BS1-BS2.

我的预期结果:

O/D BS1 BS2 BS3 BS4 BS5 BS6 BS7 BS8 BS9
BS1     2                           
BS2 1                       1       
BS3                                 
BS4                             1   
BS5 1                               
BS6                                 
BS7                                 
BS8                                 
BS9                         1   

该怎么做?非常感谢

推荐答案

以下是解决方案.

places = df["OD"].unique()
places.sort()
od_df = pd.DataFrame(df["OD"].values.reshape((-1, 2)), columns=["O", "D"])
od_matrix = od_df.groupby(["O", "D"]).size().unstack().reindex(index=places, columns=places)
od_matrix.fillna(0, downcast="infer", inplace=True)

您也可以使用pd.pivot_table并将第四行替换为

You can also use pd.pivot_table and replace the fourth line with

od_matrix = pd.pivot_table(od_df, index="O", columns="D", aggfunc="size").reindex(index=places, columns=places)

这篇关于从数据帧转换到矩阵是否有可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆