3

I have written the this code in jupyter notebook using python 3. The second column in my dataFrame is of type list. I am writing it into .csv format using the following code :

network.to_csv("network.csv", sep='\t') where "network" is my dataframe.

When I open "network.csv" file using : pd.read_csv(...). Then the second column is getting converted to type string and I want it to be a list as it was before. I am new to this. How should I go about it?

EDIT :

This the screenshot of the command I used to read the csv file.

8
  • 1
    Please tell what you use exactly to read the csv. Commented May 25, 2018 at 10:48
  • I have edited the question and have posted the screeshot. Commented May 25, 2018 at 10:56
  • Could you attach a link to an example network.csv Commented May 25, 2018 at 10:59
  • Please post code as code rather than screenshots. Commented May 25, 2018 at 11:13
  • Check this link for an example dataset : link Commented May 25, 2018 at 11:17

2 Answers 2

0

I don't think it's possible to store a list in pandas and read it as a list.

A solution I found is to use the json library to convert the string back to a list after importing the dataset:

import json
df.list = df.list.apply(lambda x:json.loads(x))
Sign up to request clarification or add additional context in comments.

1 Comment

This solution gives the following error on my data: JSONDecodeError: Expecting value: line 1 column 2 (char 1)
0

I have found a solution which works here it uses ast library

import ast
df('list').apply(ast.literal_eval)

It transforms a string like this: "['01', '02']" into a list ['01', '02']

1 Comment

the same topic is discussed here: stackoverflow.com/questions/18982584/…

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.