我有一个巨大的数据帧。数据如下所示:
Person Distance BS
A 125.58 BS3
A 212.01 BS4
B 11.41 BS3
B 134.35 BS2
C 11.41 BS3
C 274.20 BS2
D 220.98 BS5
D 8.01 BS7
E 606.05 BS1
E 676.88 BS2
F 28.81 BS7
F 98.69 BS5
G 81.64 BS1
G 35.49 BS3
我根据这个问题Is it possible from dataframe transform to Matrix?将这个数据集转换成OD矩阵,代码如下:
df = pd.read_csv("data.csv")
df = df[df.Distance < 100]
df = df[df.groupby('Person').Person.transform(len) > 1]
places = df["BS"].unique()
places.sort()
od_df = pd.DataFrame(df["BS"].values.reshape((-1, 2)), columns=["O", "D"])
od_matrix = pd.pivot_table(od_df, index="O", columns="D", aggfunc="size").reindex(index=places, columns=places)
od_matrix.fillna(0, downcast="infer", inplace=True)
od_matrix
我想消除100米以上的距离。因此,我把distance < 100
。结果如下:
D BS1 BS3 BS5 BS7
O
BS1 0 1 0 0
BS3 0 0 0 0
BS5 0 0 0 0
BS7 0 0 1 0
如果我的大数据是从BS1到BS9,在消除矩阵列和行之后,没有数据(0)也会消失。如果没有数据(0),如何显示all columns and rows事件?。我想展示矩阵如下:
D BS1 BS2 BS3 BS4 BS5 BS6 BS7 BS8 BS9
O
BS1 0 0 1 0 0 0 0 0 0
BS2 0 0 0 0 0 0 0 0 0
BS3 0 0 0 0 0 0 0 0 0
BS4 0 0 0 0 0 0 0 0 0
BS5 0 0 0 0 0 0 0 0 0
BS6 0 0 0 0 0 0 0 0 0
BS7 0 0 0 0 1 0 0 0 0
BS8 0 0 0 0 0 0 0 0 0
BS9 0 0 0 0 0 0 0 0 0
首先是将第一个筛选的
DataFrame
重新分配到df1
,通过f字符串的列表理解获得唯一的places
,并将fill_value=0
参数添加到函数pivot_table
和reindex
:或:
相关问题 更多 >
编程相关推荐