0

I have a csv column with some labels in it. I need to convert it to list of lists.
ex:

type1(heading)  
string1  
string2  
string3  
string4  

converting this directly to,

type1 = [[string1],[string2],[string3],[string4]]
4
  • so what is the issue? what did you try? Commented Oct 12, 2015 at 6:34
  • Used pandas lib to read csv and then converted the column to a list. Then, I am having problem converting it to list of lists. @AnandSKumar Commented Oct 12, 2015 at 6:49
  • Can you show the code you are currently using? Commented Oct 12, 2015 at 6:54
  • If you give an actual example piece of the file it is more worth than just some text. We need to know what differentiates the text from the headings Commented Oct 12, 2015 at 14:56

2 Answers 2

1

It seems python has a native lib to deal with such tasks. Maybe you should take a look at https://docs.python.org/2/library/csv.html

Sign up to request clarification or add additional context in comments.

Comments

1

You can try the csv module. For example, given a test.txt file:

header_a,header_b,header_c
1,2,3
4,5,6
7,8,9

You can write:

import csv

with open("test.txt", "r") as f:
    reader = csv.reader(f)
    headers = list(reader.next())
    result = [[list(c) for c in row] for row in reader]
    for i, header_name in enumerate(headers):
        print header_name, [row[i] for row in result]

The result will be:

header_a [['1'], ['4'], ['7']]
header_b [['2'], ['5'], ['8']]
header_c [['3'], ['6'], ['9']]

The document of csv module is here

2 Comments

Thank you! But I need to convert elements under same header to a list of list.
@javi_parni: I've updated my answer, see if that's what you need.

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.