0

Problem

Given:

df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = df.applymap(lambda x: [x, 0])
        0       1       2
0  [1, 0]  [2, 0]  [3, 0]
1  [4, 0]  [5, 0]  [6, 0]
2  [7, 0]  [8, 0]  [9, 0]
df.to_csv("list_entries.csv")

How do you read the data back in, preserving the original data types?


What I've Tried

This answer mentions use of converters, but I can't figure out how to apply it to all columns.

I've tried instead to use applymap():

import ast
df.applymap(lambda x: ast.literal_eval(x))

but get this error:

NameError: name 'ast' is not defined

(Follow up to this question.)

Edit:
From my debugger:

(Pdb) df.apply(lambda x: ast.literal_eval(x))
*** NameError: name 'ast' is not defined
(Pdb) ast
<module 'ast' from '/usr/lib/python3.9/ast.py'>

Edit:
Oddly it works fine outside the debugger.

young_souvlaki
  • 1,886
  • 4
  • 24
  • 28

0 Answers0