问题描述
我有这个数据框,如下图所示。我需要创建一个Origin-Destination矩阵,其中“行”轴I将以日期为列,而“来自市政代码”中的值将为“列”,在“列”轴中,我将具有“至市政代码”的值,并以填充矩阵的值将是“计数”列的值。您如何从熊猫数据框中获取矩阵?
result_final.head()
ODMatrix= pd.DataFrame(0,index=list(range(0,202708)),columns = list(range(0,202708))
).add(df.pivot_table(values='count',index="from_municipality_code",columns='to_municipality_code',aggfunc=len),fill_value=0).astype('int')
我试图将熊猫数据框转换为numpy数组,但是没有用。
result_final[['date','from_municipality_code','to_municipality_code','count','Lng_x','Lat_x','Lng_y','Lat_y',]].to_numpy()
这是我想要的最终矩阵,如果它有助于可视化:
解决方法
您可以使用pivot_table
方法。这是一个工作示例:
import pandas as pd
import numpy as np
# Some example data
df = pd.DataFrame({"from": np.random.randint(0,10,(1000,)),"to": np.random.randint(0,))})
# Remove examples where from == to
df = df.loc[df["from"] != df["to"]].copy()
# The key operation
matrix = (
df.assign(count=1)
.pivot_table(index="from",columns="to",values="count",aggfunc="count")
.fillna(0)
.astype(int)
)
print(matrix)
to 0 1 2 3 4 5 6 7 8 9
from
0 0 10 14 7 9 14 18 6 11 8
1 11 0 12 7 4 12 9 11 6 13
2 6 14 0 12 13 8 5 15 11 10
3 10 9 12 0 14 10 8 14 9 11
4 10 14 14 11 0 8 4 10 11 4
5 15 10 10 18 8 0 15 15 8 12
6 9 7 10 13 10 8 0 11 12 10
7 9 12 4 6 9 9 8 0 8 12
8 8 8 11 12 15 10 11 4 0 6
9 10 13 11 16 14 18 11 9 4 0