【问题标题】:Is it possible from dataframe transform to Matrix?是否可以从数据框转换为矩阵?
【发布时间】:2019-06-10 04:43:39
【问题描述】:

我是python的新手, 我有一个巨大的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。

我的预期结果:

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   

怎么做?非常感谢

【问题讨论】:

  • 输入数据是否总是每个人连续两行,第一行是原点?
  • 是的,确实如此,而且数据总是成对的。第一行是起点,第二行是终点

标签: python pandas dataframe matrix multiple-columns


【解决方案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 并将第四行替换为

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

【讨论】:

    猜你喜欢
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多