【问题标题】:How to merge cells with list datatypes from different dataframes in Python Pandas?如何在 Python Pandas 中将单元格与来自不同数据帧的列表数据类型合并?
【发布时间】:2021-08-16 14:55:13
【问题描述】:

我目前正在尝试使用 pandas 将来自两个不同数据框的列表合并在一起。我试图让 df1 中的每个单元格合并 df2 中的所有单元格。例如,我有以下两个数据框:

>>> df1
0   [This, is, a, sentence]
1   [this, is, another, sentence]

>>> df2
0   [this, is, also, a, sentence]
1   [this, too, is, a, sentence]
2   [this, is, very, different]
3   [another, sentence, is, this]
4   [not, much, of, anything]

我正在尝试将 df1 中的两个单元格与 df2 中的单元格合并,以提供以下输出:

>>> df_merged
0   [this, is, also, a, sentence, This, is, a, sentence]   
1   [this, too, is, a, sentence, This, is, a, sentence]       
2   [this, is, very, different, This, is, a, sentence]       
3   [another, sentence, is, this, This, is, a, sentence]     
4   [not, much, of, anything, This, is, a, sentence]       

>>> df2_merged
0   [this, is, also, a, sentence, This, is, another, sentence]   
1   [this, too, is, a, sentence, This, is, another, sentence]     
2   [this, is, very, different, This, is, another, sentence]      
3   [another, sentence, is, this, This, is, another, sentence]   
4   [not, much, of, anything, This, is, another, sentence]     

关于如何实现这一目标的任何想法?它们不一定需要拆分为不同的数据帧,它们可以位于同一数据帧的不同列中等

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    Cross 加入两个数据框,然后连接两个列表:

    df1.join(df2, how='cross', lsuffix='1', rsuffix='2').apply(lambda x: x['text2']+x['text1'], axis=1)
    

    输出:

    0          [this, is, also, a, sentence, This, is, a, sentence]
    1           [this, too, is, a, sentence, This, is, a, sentence]
    2            [this, is, very, different, This, is, a, sentence]
    3          [another, sentence, is, this, This, is, a, sentence]
    4              [not, much, of, anything, This, is, a, sentence]
    5    [this, is, also, a, sentence, this, is, another, sentence]
    6     [this, too, is, a, sentence, this, is, another, sentence]
    7      [this, is, very, different, this, is, another, sentence]
    8    [another, sentence, is, this, this, is, another, sentence]
    9        [not, much, of, anything, this, is, another, sentence]
    dtype: object
    

    用于上述代码的数据(df1 和 df2 有 text 列):

    >>> df1
                                text
    0        [This, is, a, sentence]
    1  [this, is, another, sentence]
    
    >>> df2
                                text
    0  [this, is, also, a, sentence]
    1   [this, too, is, a, sentence]
    2    [this, is, very, different]
    3  [another, sentence, is, this]
    4      [not, much, of, anything]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 2021-11-22
      • 2022-11-29
      • 2021-08-21
      • 2016-10-17
      • 1970-01-01
      相关资源
      最近更新 更多