我正在尝试从 Excel 工作表中的两列创建一个矩阵。第一列是具有多个重复实例的键,第二列引用与该键相关的不同值。我希望能够创建第二列中所有值的矩阵,以引用它们针对所有关键实例配对在一起的次数。
a b
1 red
1 blue
1 green
2 yellow
2 red
3 blue
3 green
3 yellow
我想将此示例数据框转换为
color red blue yellow green
red 0 1 1 1
blue 1 0 1 2
yellow 1 1 0 1
green 1 2 1 0
本质上使用 a 列作为 groupby() 来分段每个键,然后对遇到的关系进行计数作为运行计数。不太清楚如何实现数据透视表或交叉表来完成此任务(如果这是最好的路线)。
最佳答案
使用how='cross'
作为pd.merge
的参数。我假设您没有像两个(1,红色)那样的('a','b')重复项。
out = (
pd.merge(df, df, how='cross').query('a_x == a_y & b_x != b_y')[['b_x', 'b_y']] \
.assign(dummy=1).pivot_table('dummy', 'b_x', 'b_y', 'count', fill_value=0) \
.rename_axis(index=None, columns=None)
)
print(out)
# Output:
blue green red yellow
blue 0 2 1 1
green 2 0 1 1
red 1 1 0 1
yellow 1 1 1 0
关于python - 从两列创建一个矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70370709/