【问题标题】:Column-wise string concatenation of multiple rows in pandas.DataFrame with specific separator具有特定分隔符的 pandas.DataFrame 中多行的按列字符串连接
【发布时间】:2021-06-09 11:38:22
【问题描述】:

有没有一种有效的方法来连接DataFrame多行的字符串,这样结果是单行,每列的值是同一列的每个值的连接所有给定的行数?

示例

如前所述合并前四行。

>>> df = pd.DataFrame([["this", "this"], ["is", "is"], ["a", "a"], ["test", "test"], ["ignore", "ignore"]])
>>> df
        0       1
0    this    this
1      is      is
2       a       a
3    test    test
4  ignore  ignore

两个都接受的结果:

          0              1
0  this is a test  this is a test
          0
1  this is a test
2  this is a test

【问题讨论】:

    标签: pandas dataframe concatenation series pd


    【解决方案1】:

    如果需要连接所有行而不使用最后一次使用DataFrame.ilocDataFrame.agg

    s = df.iloc[:-1].agg(' '.join)
    print (s)
    0    this is a test
    1    this is a test
    dtype: object
    

    对于一行DataFrame 添加Series.to_frame 与转置:

    df = df.iloc[:-1].agg(' '.join).to_frame().T
    print (df)
                    0               1
    0  this is a test  this is a test
    

    对于所有行:

    s = df.agg(' '.join)
    print (s)
    0    this is a test ignore
    1    this is a test ignore
    dtype: object
    
    
    df = df.agg(' '.join).to_frame().T
    print (df)
                           0                      1
    0  this is a test ignore  this is a test ignore
    

    【讨论】:

    • 非常感谢您的回答,jezrael。我针对我的解决方案df.iloc[rows, :].apply(lambda column: " ".join(column), axis=0)rows 是一个由行索引组成的列表)对其进行了测试,并且两者的表现都一样好。也许我们会找到更好的解决方案!
    • @cspecial - 是的,这是一个很好的解决方案,类似于我的回答,axis=0 是默认值,所以应该删除。
    猜你喜欢
    • 2015-04-10
    • 2018-04-21
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    相关资源
    最近更新 更多