amiref
amiref

Reputation: 3441

Changing array objects to string in pandas

I have the following pandas dataframe:

df11 = pd.DataFrame(columns=["col1", "col2", "col3"])
df11.loc[1] = [2,["a","q","v"],["g","h","v"]]
df11.loc[2] = [21,["b","z","o"],["h"]]
df11.loc[3] = [11,["g","s","v"],["g","h","v"]]
df11.loc[4] = [2,["a","q","v"],["n","m","k","p"]]

How I can replace the arrays in col2 and col3 with their string equivalent? like this:

df11 = pd.DataFrame(columns=["col1", "col2", "col3"])
df11.loc[1] = [2,"a,q,v","g,h,v"]
df11.loc[2] = [21,"b,z,o","h"]
df11.loc[3] = [11,"g,s,v","g,h,v"]
df11.loc[4] = [2,"a,q,v","n,m,k,p"]

Upvotes: 2

Views: 45

Answers (1)

jezrael
jezrael

Reputation: 863501

Use str.join with list of columns names in loop:

cols = ['col2','col3']
for c in cols:
    df11[c] = df11[c].str.join(',')

Or use applymap:

df11[cols] = df11[cols].applymap(','.join)

Or list comprehension solution:

L = [[','.join(y for y in x) for x in df11[c]] for c in cols]
df11[cols] = pd.DataFrame(L, columns=df11.index).T

print (df11)
  col1   col2     col3
1    2  a,q,v    g,h,v
2   21  b,z,o        h
3   11  g,s,v    g,h,v
4    2  a,q,v  n,m,k,p

Upvotes: 3

Related Questions