Petr Petrov
Petr Petrov

Reputation: 4442

Pandas: convert all columns in dataframe to string

I have dataframe

 0     1     2
12     34   23
10     12    0

Desire output

upd_string
12, 34, 23
10, 12, 0

I try

df_upd = pd.DataFrame()
df_upd['upd_string'] = df[df.columns.values.tolist()].apply(str)

But it returns

ValueError: no results

Upvotes: 1

Views: 4444

Answers (1)

jezrael
jezrael

Reputation: 862641

First cast to strings if numeric and then apply join:

df.astype(str).apply(', '.join, axis=1)

for new DataFrame:

df_upd = pd.DataFrame({'upd_string': df.astype(str).apply(', '.join, axis=1)})
print (df_upd)
   upd_string
0  12, 34, 23
1   10, 12, 0

Upvotes: 4

Related Questions