I currently have dataframe at the top. Is there a way to use a groupby function to get another dataframe to group the data and concatenate the words into the format like further below using python pandas?
Thanks
[
Advertisement
Answer
You can apply join
on your column after groupby
:
JavaScript
x
2
1
df.groupby('index')['words'].apply(','.join)
2
Example:
JavaScript
1
22
22
1
In [326]:
2
df = pd.DataFrame({'id':['a','a','b','c','c'], 'words':['asd','rtr','s','rrtttt','dsfd']})
3
df
4
5
Out[326]:
6
id words
7
0 a asd
8
1 a rtr
9
2 b s
10
3 c rrtttt
11
4 c dsfd
12
13
In [327]:
14
df.groupby('id')['words'].apply(','.join)
15
16
Out[327]:
17
id
18
a asd,rtr
19
b s
20
c rrtttt,dsfd
21
Name: words, dtype: object
22