How to combine multiple rows of strings into one using pandas?

前端 未结 4 1482
情话喂你
情话喂你 2021-02-01 19:12

I have a DataFrame with multiple rows. Is there any way in which they can be combined to form one string?

For example:

     words
0    I, will, hereby
1         


        
4条回答
  •  无人及你
    2021-02-01 19:37

    If you have a DataFrame rather than a Series and you want to concatenate values (I think text values only) from different rows based on another column as a 'group by' key, then you can use the .agg method from the class DataFrameGroupBy. Here is a link to the API manual.

    Sample code tested with Pandas v0.18.1:

    import pandas as pd
    
    df = pd.DataFrame({
        'category': ['A'] * 3 + ['B'] * 2,
        'name': ['A1', 'A2', 'A3', 'B1', 'B2'],
        'num': range(1, 6)
    })
    
    df.groupby('category').agg({
        'name': lambda x: ', '.join(x),
        'num': lambda x: x.max()
    })
    

提交回复
热议问题