2

I have a dataframe with many columns

df=
                                                    c1\
2015-01-01  [50.4750711276, 50.4750711276, 50.4750711276]   
2015-01-02  [50.5349107929, 50.5349107929, 50.5349107929]     

                                                   c2
2015-01-01  [33.5322374641, 33.5322374641, 33.5322374641]  
2015-01-02  [33.4770757092, 33.4770757092, 33.4770757092]  

I would like to split each column into columns containing the single elements of the lists. Like (for c1)

          0          1          2
0  50.475071  50.475071  50.475071
1  50.534911  50.534911  50.534911

I can do

pd.DataFrame(df.c1.values.tolist()).add_prefix('code_')

but how to do it for all the columns at the same time and being able to add a prefix based on the name of the column?

1 Answer 1

3

Use list comprehension with concat:

comp = [pd.DataFrame(df[x].values.tolist(), index=df.index).add_suffix('_code_' + x) 
         for x in df.columns]
df = pd.concat(comp, axis=1)
print (df)
            0_code_c1  1_code_c1  2_code_c1  0_code_c2  1_code_c2  2_code_c2
2015-01-01  50.475071  50.475071  50.475071  33.532237  33.532237  33.532237
2015-01-02  50.534911  50.534911  50.534911  33.477076  33.477076  33.477076

EDIT:

names = list('ABC')
comp = [pd.DataFrame(df[x].values.tolist(), index=df.index, columns=names).add_suffix('_' + x)
         for i, x in enumerate(df.columns)]
df = pd.concat(comp, axis=1)
print (df)
                 A_c1       B_c1       C_c1       A_c2       B_c2       C_c2
2015-01-01  50.475071  50.475071  50.475071  33.532237  33.532237  33.532237
2015-01-02  50.534911  50.534911  50.534911  33.477076  33.477076  33.477076
Sign up to request clarification or add additional context in comments.

1 Comment

can I replace the int_ which is automatically added to each column name at beginning? I have a list of strings same len as the columns of df

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.