如何交叉连接 2 个系列以使其在 pandas 中查找 table?

How to cross join 2 series to make it a lookup table in pandas?

我正在尝试创建一个包含 ID 和日期交叉连接的引用 table,并将使用此 table 作为左连接 table 来执行所有操作。请告知如何通过系列交叉连接从 2 个系列制作数据框。

我将系列 1 创建为:

df1 = pd.Series(pd.date_range(start='1/1/2017', end='1/1/2019', freq='MS'))
df2 = pd.Series(["AN", "BN", "CN"])

我想要一个像这样的 df:

id dt
AN 1-1-2017
AN 1-2-2017
..
BN 1-1-2017
BN 1-2-2017
..
CN 1-1-2017
CN 1-2-2017
and so on..

itertools.productDataFrame 构造函数一起使用:

from  itertools import product
df = pd.DataFrame(list(product(df2, df1)), columns=['id','dt'])
#pandas 0.25+ list should be omit
#df = pd.DataFrame((product(df2, df1)), columns=['id','dt'])
print (df)
    id         dt
0   AN 2017-01-01
1   AN 2017-02-01
2   AN 2017-03-01
3   AN 2017-04-01
4   AN 2017-05-01
..  ..        ...
70  CN 2018-09-01
71  CN 2018-10-01
72  CN 2018-11-01
73  CN 2018-12-01
74  CN 2019-01-01

[75 rows x 2 columns]

这是使用 explode 的方法:

# convert series to dataframe
df3 = df1.reset_index().drop('index', 1)

# add a new row
df3['dt'] = [df2.values.tolist() for _ in range(df3.shape[0])]

# explode the new row
df3 = df3.explode('dt')