显示所有0值的变换矩阵

2024-10-01 19:22:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个巨大的数据帧。数据如下所示:

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

Tags: columns数据dfbs矩阵personpdplaces
1条回答
网友
1楼 · 发布于 2024-10-01 19:22:54

首先是将第一个筛选的DataFrame重新分配到df1,通过f字符串的列表理解获得唯一的places,并将fill_value=0参数添加到函数pivot_tablereindex

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

相关问题 更多 >

    热门问题