2

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"]

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.