1

I have this pd.DataFrame() created. I want to create a .csv and it is saving as this

                                                         0  1
0        [15921, 10, 82, 22, 202973, 368, 1055, 3135, 1...  0
1        [609, 226, 413, 363, 211, 241, 988, 80, 12, 19...  0
2        [22572, 3720, 233, 13, 827, 710, 512, 354, 1, ...  0
3                             [345, 656, 25, 2589, 6, 866]  0
4                                [29142, 8, 4141, 456, 24]  0
                                                   ... ..
1599995                         [256, 8, 80, 110, 25, 152]  4
1599996  [609039, 22, 129, 184, 163, 9419, 769, 358, 10...  4
1599997                       [140, 5715, 6540, 294, 1552]  4
1599998  [59, 22771, 189, 387, 4483, 13, 10305, 112231,...  4
1599999                [59, 15833, 200370, 609041, 609042]  4

but by doing

data.to_csv("foo.csv", index=True)

The problem is that each list is now saved as str. For example, row 3 is

"[345, 656, 25, 2589, 6, 866]"

And for those skeptics, I've tried type(row 3) and it's str. Column 2 is working well.

How can I save as list each row and not as str? That is, how can I save all rows of col 1as DataFrame and not as str?

Omar
  • 1,029
  • 2
  • 13
  • 33
  • 1
    Does this answer your question? [Pandas DataFrame stored list as string: How to convert back to list?](https://stackoverflow.com/questions/23111990/pandas-dataframe-stored-list-as-string-how-to-convert-back-to-list) – Michael Szczesny Oct 03 '20 at 10:28
  • @mikksu no sorry it doesn't answer my question – Omar Oct 03 '20 at 10:38

1 Answers1

2

Try this:

import pandas as pd

df = pd.DataFrame({'a': ["[1,2,3,4]", "[6,7,8,9]"]})
df['b'] = df['a'].apply(eval)
print(df)

The data in column b is now an array.

           a             b
0  [1,2,3,4]  [1, 2, 3, 4]
1  [6,7,8,9]  [6, 7, 8, 9]
divingTobi
  • 2,044
  • 10
  • 25
  • Thank you! It worked, but I changed one thing: `df['a'] = df['a'].apply(eval)` to change `col a` to `list` and `df['b'] = df['b'].apply(eval)` to do the same with `col b` – Omar Oct 03 '20 at 10:44