我有一个巨大的数据框。数据如下所示:
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
我根据这个问题将这个数据集转换成OD矩阵Is it possible from dataframe transform to Matrix?使用此代码:
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),如何显示所有列和行事件?我想显示的矩阵如下所示:
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=函数
参数:pivot_table
和 reindex
的 0
df1 = df[df.Distance < 100]
df1 = df1[df1.groupby('Person').Person.transform(len) > 1]
places = [f'BS{ x + 1}' for x in range(9)]
print (places)
['BS1', 'BS2', 'BS3', 'BS4', 'BS5', 'BS6', 'BS7', 'BS8', 'BS9']
od_df = pd.DataFrame(df1["BS"].values.reshape((-1, 2)), columns=["O", "D"])
od_matrix = (pd.pivot_table(od_df, index="O", columns="D", aggfunc="size", fill_value=0)
.reindex(index=places, columns=places, fill_value=0))
或者:
od_matrix = (pd.crosstab(od_df["O"], od_df["D"])
.reindex(index=places, columns=places, fill_value=0))
<小时/>
print (od_matrix)
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
关于python - 变换矩阵 - 显示所有 0 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56662017/