我有极地数据帧

data = {
    "col1": ["a", "b", "c", "d"],
    "col2": [[-0.06066, 0.072485, 0.548874, 0.158507],
             [-0.536674, 0.10478, 0.926022, -0.083722],
             [-0.21311, -0.030623, 0.300583, 0.261814],
             [-0.308025, 0.006694, 0.176335, 0.533835]],
}

df = pl.DataFrame(data)

我想为第col1列的每个组合计算余弦相似度

所需的输出应如下所示:

┌─────────────────┬──────┬──────┬──────┬──────┐
│ col1_col2       ┆ a    ┆ b    ┆ c    ┆ d    │
│ ---             ┆ ---  ┆ ---  ┆ ---  ┆ ---  │
│ str             ┆ f64  ┆ f64  ┆ f64  ┆ f64  │
╞═════════════════╪══════╪══════╪══════╪══════╡
│ a               ┆ 1.0  ┆ 0.86 ┆ 0.83 ┆ 0.54 │
│ b               ┆ 0.86 ┆ 1.0  ┆ 0.75 ┆ 0.41 │
│ c               ┆ 0.83 ┆ 0.75 ┆ 1.0  ┆ 0.89 │
│ d               ┆ 0.54 ┆ 0.41 ┆ 0.89 ┆ 1.0  │
└─────────────────┴──────┴──────┴──────┴──────┘

其中每个值表示各个列值之间的余弦相似度.

我试着用pivot个方法

df.pivot(values="col2", index="col1", columns="col1", aggregate_function=cosine_similary)

但是,我收到以下错误

'function' object has no attribute '_pyexpr'

我正在使用下面的余弦相似函数

from numpy.linalg import norm

cosine_similarity = lambda a,b: (a @ b.T) / (norm(a)*norm(b))

但是,我可以使用它的任何实现

推荐答案

您可以交叉联接+筛选器来获得配对.(即combinations_with_replacements(..., r=2))

并使用表达式进行相似性计算:

x = pl.col("col2").flatten()
y = pl.col("col2_right").flatten()

row = pl.first().cum_count()

cosine_similarity = (
   x.dot(y) / (x.pow(2).sum().sqrt() * y.pow(2).sum().sqrt())
).over(row)

(df.join(df, how = "cross")
   .filter(pl.col("col1") <= pl.col("col1_right"))
   .select(
      col    = "col1",
      other  = "col1_right",
      cosine = cosine_similarity
   )
)
shape: (10, 3)
┌─────┬───────┬──────────┐
│ col ┆ other ┆ cosine   │
│ --- ┆ ---   ┆ ---      │
│ str ┆ str   ┆ f64      │
╞═════╪═══════╪══════════╡
│ a   ┆ a     ┆ 1.0      │
│ a   ┆ b     ┆ 0.856754 │
│ a   ┆ c     ┆ 0.827877 │
│ a   ┆ d     ┆ 0.540282 │
│ b   ┆ b     ┆ 1.0      │
│ b   ┆ c     ┆ 0.752199 │
│ b   ┆ d     ┆ 0.411564 │
│ c   ┆ c     ┆ 1.0      │
│ c   ┆ d     ┆ 0.889009 │
│ d   ┆ d     ┆ 1.0      │
└─────┴───────┴──────────┘

如果需要,您可以 Select .pivot.

Python相关问答推荐

在Python中是否可以输入使用任意大小参数列表的第一个元素的函数

如何匹配3D圆柱体的轴和半径?

模型序列化器中未调用现场验证器

更改Seaborn条形图中的x轴日期时间限制

在Pandas框架中截短至固定数量的列

将HTML输出转换为表格中的问题

使用pandas、matplotlib和Yearbox绘制时显示错误的年份

比较两个二元组列表,NP.isin

如何使用Jinja语法在HTML中重定向期间传递变量?

如何在BeautifulSoup中链接Find()方法并处理无?

按顺序合并2个词典列表

在Mac上安装ipython

如何让这个星型模式在Python中只使用一个for循环?

Pandas计数符合某些条件的特定列的数量

Asyncio:如何从子进程中读取stdout?

使用groupby方法移除公共子字符串

如何合并两个列表,并获得每个索引值最高的列表名称?

如何使用SentenceTransformers创建矢量嵌入?

Pandas Data Wrangling/Dataframe Assignment

Pandas:填充行并删除重复项,但保留不同的值