【问题标题】:Compute matrix of outer operations on pandas series计算 pandas 系列的外部操作矩阵
【发布时间】:2023-03-07 19:50:02
【问题描述】:

我有一个系列,其中索引是标签(字符串),值是向量。

我想将系列与自身进行外部连接,其中元素是两个向量的点积。

M_ij = sum over k (x_ik*x_jk)

其中 x_i 是序列中的第 i 个元素,k 是向量的索引(并且相加)

我知道我可以将我的系列显式转换为矩阵并执行此操作,但我想知道是否有一种“正确”的方法可以使用系列/DataFrame 对象对熊猫进行操作。我也喜欢保留这些向量的标签的想法。

编辑:

示例数据

x= pd.Series({
'label1': [0,1],
'label2': [1,0],
'label3': [1,1]})

M = function_i_want(x)

M = 

1 0 1
0 1 1
1 1 2

编辑2:

这是 numpy 的做法

np.dot(np.stack(x),np.stack(x).T)

但我更希望它作为系列来生成一个数据框,其中包含适当的列/索引标签。

【问题讨论】:

  • 你能提供一个数据样本和预期的输出吗?例如,对于 [1, 2, 3, 4, 5],期望什么?
  • 您在寻找np.outer吗?
  • 我添加了数据示例。它不完全是 np.outer,因为它会生成两个向量的外积。我想将自定义操作(内积)应用于两个系列的外连接。感谢您的帮助!
  • 所有向量都具有相同的维度吗? (我希望)
  • 是的,他们有。我确实可以使用 np.dot(np.stack(x),np.stack(x).T) 在 numpy 中做到这一点。但我想要一个数据框,这样我就可以通过使用标签而不是 indecies 来访问事物。即我想写 M['label1'] 并查看名为 label1 的向量与所有其他向量的点积。

标签: python pandas numpy dataframe series


【解决方案1】:

这是使用 numpy 的更好方法 -

y = np.array(x.tolist())
pd.DataFrame(y.dot(y.T), index=x.index, columns=x.index)

        label1  label2  label3
label1       1       0       1
label2       0       1       1
label3       1       1       2

熊猫之路 -

df = pd.DataFrame(x.tolist(), index=x.index)
df.dot(df.T)

        label1  label2  label3
label1       1       0       1
label2       0       1       1
label3       1       1       2

【讨论】:

    猜你喜欢
    • 2021-04-03
    • 2014-01-20
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    相关资源
    最近更新 更多