通过外连接将 pandas 数据框与列表合并

Nic*_*ick 3 python list pandas

我有一个如下所示的数据框

   A  B
0  1  4
1  2  5
2  3  6
Run Code Online (Sandbox Code Playgroud)

和一个清单

names = ['x','y']
Run Code Online (Sandbox Code Playgroud)

我想获得一个能够执行该列表并进行外部连接的数据框。期望的结果是:

   A  B  name
0  1  4  x
1  1  4  y
2  2  5  x
3  2  5  y
4  3  6  x
5  3  6  y
Run Code Online (Sandbox Code Playgroud)

jpp*_*jpp 5

使用pd.concat

res = pd.concat([df.assign(name=i) for i in names], ignore_index=True)
Run Code Online (Sandbox Code Playgroud)

结果:

   A  B name
0  1  4    x
1  2  5    x
2  3  6    x
3  1  4    y
4  2  5    y
5  3  6    y
Run Code Online (Sandbox Code Playgroud)