我有一个Pandas DataFrame,看起来像这样:

df = pd.DataFrame({'col1': [1, 2, 3],
                   'col2': [4, 5, 6],
                   'col3': [7, 8, 9]})

df
    col1    col2    col3
0      1       4       7
1      2       5       8
2      3       6       9

我想像这样创建一个Pandas DataFrame:

df_new
    col1    col2    col3
0      1       4       7
1      1       5       8
2      1       6       9
3      2       4       7
4      2       5       8
5      2       6       9
6      3       4       7
7      3       5       8
8      3       6       9

有没有内置或组合的内置Pandas 方法可以实现这一点?

即使在df中有重复,我也希望输出是相同的格式.换句话说:

df
    col1    col2    col3
0      1       4       7
1      2       5       8
2      2       6       8

df_new
    col1    col2    col3
0      1       4       7
1      1       5       8
2      1       6       8
3      2       4       7
4      2       5       8
5      2       6       8
6      2       4       7
7      2       5       8
8      2       6       8

提前感谢您的任何建议!

推荐答案

我也会像@Henry在 comments 中建议的那样, Select 一个十字merge:

out = df[['col1']].merge(df[['col2', 'col3']], how='cross').reset_index(drop=True)

输出:

   col1  col2  col3
0     1     4     7
1     1     5     8
2     1     6     9
3     2     4     7
4     2     5     8
5     2     6     9
6     3     4     7
7     3     5     8
8     3     6     9

不同方法的比较:

enter image description here

Note that @sammywemmy's approach behaves differently when rows are duplicated, which leads to a non comparable timing.

Python相关问答推荐

为什么图像结果翻转了90度?

Django关于UniqueBindition的更新

如何在Pandas 中存储二进制数?

在Python中添加期货之间的延迟

使用decorator 重复超载

调试回归无法解决我的问题

在Python中根据id填写年份系列

Python中使用时区感知日期时间对象进行时间算术的Incredit

比较2 PD.数组的令人惊讶的结果

抓取rotowire MLB球员新闻并使用Python形成表格

在Pandas DataFrame操作中用链接替换'方法的更有效方法

用合并列替换现有列并重命名

数据抓取失败:寻求帮助

如何在python polars中停止otherate(),当使用when()表达式时?

OR—Tools CP SAT条件约束

pyscript中的压痕问题

关于Python异步编程的问题和使用await/await def关键字

将输入聚合到统一词典中

如何指定列数据类型

人口全部乱序 - Python—Matplotlib—映射