1

I have imported a .csv file into Python and named it data. It looks something like this:

aK    bK    id
.124  .121  1
.320  .202  2
.222  .198  3

And so on for a few hundred rows. How do I convert column aK and column bK into lists? I have tried this:

aK = []
for row in data:
    aK.append(row[0])

But aK is still a blank list.

7
  • how u imported csv in data?? Commented Dec 24, 2014 at 16:43
  • Can you clarify that question please Commented Dec 24, 2014 at 16:44
  • @japem I think he's asking how you loaded the file and converted it to a python string/list/other object. Were you using the csv module? Commented Dec 24, 2014 at 16:45
  • Oh. Yes I was. >>> Import csv >>> a = open('MyFile.csv') >>> data = csv.reader(a) Commented Dec 24, 2014 at 16:46
  • 1
    @japem For the code you've posted in comment it's hard to belive aK is empty after the loop, post the actual code in question body.(Perhaps you consumed the file object before you passed it to csv.reader) Commented Dec 24, 2014 at 16:50

2 Answers 2

3
import csv

CSV_FILE = "test.csv"

def main():
    with open(CSV_FILE) as inf:
        in_csv = csv.reader(inf, delimiter=" ", skipinitialspace=True)
        header = next(in_csv)       # skip header row
        ak, bk, id = zip(*in_csv)   # get columns

if __name__ == "__main__":
    main()

which gives

ak = ('.124', '.320', '.222')
bk = ('.121', '.202', '.198')
id = ('1', '2', '3')
Sign up to request clarification or add additional context in comments.

4 Comments

Is the "test.csv" file the one I originally imported?
@Hackaholic - Why reinvent the wheel? Importing a module is trivial in Python. Besides, the csv module will be more robust than anything handcrafted.
@iCodez this 4 line of code, i dont think reinvent the whell, and all this csv module make use of this built function like split and strip only
@HughBothwell I can see why you looked for delimiter=" " skipping initial spaces. That makes sense for the data on this website but I think it's very likely OP had used a tab delimited file and Stackoverflow converted them to spaces or the text editor did
0

The way you approached it seems fine. You just didn't show how you created data

>>> import csv
>>> with open('data.csv') as f:
        aK, bK = [], []
        next(f) # skip headers
        for row in csv.reader(f, delimiter='\t'):
            aK.append(float(row[0]))
            bK.append(float(row[1]))


'aK\tbK\tid\n'
>>> aK
[0.124, 0.32, 0.222]
>>> bK
[0.121, 0.202, 0.198]

Comments

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.