python - 复制并合并两个数据框 pandas

标签 python python-3.x pandas list join

背景

我有两个样本 df

这里是df1

import pandas as pd
l =  [list(['ABC', 'DEF', 'GHI'])]
df1 = pd.DataFrame({'Letters': l})

df1
      Letters
 0  [ABC, DEF, GHI]

df2

df2 = pd.DataFrame({'Text' : ['Hi ', 
                                       'hey', 
                                       'hello ',
                                        'bye',
                                        'see ya'
                            ], 

                          'ID': [1,2,3, 4,5]
                         })
df2     
        ID Text
    0   1   Hi
    1   2   hey
    2   3   hello
    3   4   bye
    4   5   see ya

期望的输出

    ID Text  Letters
0   1   Hi     [ABC, DEF, GHI]
1   2   hey    [ABC, DEF, GHI]
2   3   hello  [ABC, DEF, GHI]
3   4   bye    [ABC, DEF, GHI]
4   5   see ya [ABC, DEF, GHI]

问题

如何复制 df1 并将其与 df2 组合以获得所需的输出?

最佳答案

你可以这样做:

df2=df2.assign(**pd.concat([df1]*len(df2),ignore_index=True))

或者:

df2=df2.assign(Letters=np.resize(df1.to_numpy(),len(df2))) #df1.values for lower versions

     Text  P_ID          Letters
0     Hi      1  [ABC, DEF, GHI]
1     hey     2  [ABC, DEF, GHI]
2  hello      3  [ABC, DEF, GHI]
3     bye     4  [ABC, DEF, GHI]
4  see ya     5  [ABC, DEF, GHI]

关于python - 复制并合并两个数据框 pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57444260/

相关文章:

python - matplotlib 怪异,它没有绘制我的图表

python: e驱动器的os.walk不起作用

python - 计算混合文本文件中特定数字的平均值?

python - 如何将列合并为 Python 中的单个列?

python - 使用 Pandas reshape 2 列的数据

python - 如何对 pandas 数据框进行非规范化

python - SQLAlchemy 是否可以在多个 Python 进程之间共享 SQLite 数据库?

python - 为什么我使用 pandas 和 xlsxwriter 时会出现值错误?

python-3.x - 如何通过在 Django 2.0 中创建语言文件来集成多语言支持?

python - 通过非匹配标准聚合 pandas 数据框的更好方法