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
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()
})