如何对 numpy 数组和 pandas 系列进行笛卡尔连接?

问题描述 投票:0回答:3

我有一个 numpy 数组

ids
(唯一)和一个 pandas 系列
dates

我想创建一个 pandas 数据框,它是

ids
dates
的笛卡尔积,其中列
id
date
按日期分组。

例如,

ids = [1, 2]
dates = [10032023, 10042023]
,以及生成的数据框:

id     date
1      10032023
2      10032023
1      10042023
2      10042023

我似乎不知道如何使用 pandas 中现有的矢量化操作来做到这一点。我当前的方法只是迭代两者并单独分配行。

python pandas cartesian-product
3个回答
0
投票

您可以使用内置

product
模块中的
itertools
方法来实现此目的。

笛卡尔积是这样完成的:

from itertools import product

array1 = [1, 2, 3]
array2 = ['a', 'b']

result = list(product(array1, array2))
print(result)

结果如下:

[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]

文档在这里:https://docs.python.org/3/library/itertools.html#itertools.product

文档指出这不是矢量化的,但实际上是这样的:

大致相当于生成器表达式中的嵌套 for 循环。例如,

product(A, B)
返回与
((x,y) for x in A for y in B)
相同的结果。


0
投票

pd.merge 在这种情况下应该可以工作,我们应该只指定

how=cross
来进行叉积。我们还需要将初始 ndarray 转换为 Series 并确保两者都被命名。如果任何系列未命名,我们可以用
series.name = "hoopla"
来处理。

这是一个演示,假设您已经创建了一个系列和 numpy 数组,我们只需要最后两行:

import pandas as pd
import numpy as np

arr = np.array([1,2])

df2 = df.Series([10032023, 10042023], name="df2")

df1 = pd.Series(arr, name="df1")
cross_prod = pd.merge(df1, df2, how="cross")

希望有帮助!


0
投票

使用

MultiIndex.from_product

ids = [1, 2]
dates = [10032023, 10042023]
out = pd.MultiIndex.from_product([dates, ids]).to_frame(index=False)\
        .reindex([1, 0], axis=1).set_axis(['id', 'date'], axis=1)

    id  date
0   1   10032023
1   2   10032023
2   1   10042023
3   2   10042023
© www.soinside.com 2019 - 2024. All rights reserved.