Ambri
Ambri

Reputation: 47

Concatenate a DataFrame column into a String

I have a DataFrame like below:

column_A   column_B
  2           4 
  7           1  
 Seven      Three
  34         23

I would like to return the values of column_A and column_B as a single string like below:

concatenated_A = 2, 7, Seven, 34
concatenated_B = 4, 1, Three, 23

I have tried to the below code:

concatenated_A = df[column_A].to_json()
print(concatenated_A)

But it is getting printed like below:

{"0":"2", "1":"7", "2":"Seven", "3":"34"}

Any help would be appreciated.

Upvotes: 1

Views: 92

Answers (2)

BENY
BENY

Reputation: 323266

Get two columns output

df.apply(', '.join)
Out[41]: 
column_A    2, 7, Seven, 34
column_B    4, 1, Three, 23
dtype: object

Upvotes: 1

rafaelc
rafaelc

Reputation: 59274

Use str.cat

>>> df.column_A.str.cat(sep=' ')
'2 7 Seven 34'

Upvotes: 3

Related Questions