简体   繁体   中英

accessing the values of collections.defaultdict

I have a csv file that I want to read column wise, for that I've this code :

from collections import  defaultdict
from csv import DictReader

columnwise_table = defaultdict(list)
with open("Weird_stuff.csv",'rU') as f:
    reader = DictReader(f)
    for row in reader:
        for col,dat in row.items():
            columnwise_table[col].append(dat)
#print(columnwise_table.items())  # this gives me everything 

print(type(columnwise_table[2]) # I'm look for smt like this 

my question is how can get all the element of only one specific column ? and I'm not using conda and the matrix is big 2400x980

UPDATE

I have 980 columns and over 2000 rows I need to work with the file using the columns say 1st column[0]: feature1 2nd column[0]: j_ss01 50th column: Abs2 and so on
since I can't access the dict using the column names I would like to use an index for that. is this possible ?

By iterating on row.items, you get all columns.

If you want only one specific column via index number, use csv.reader and column index instead.

from csv import reader

col_values = []
# Column index number to get values from
col = 1

with open("Weird_stuff.csv",'rU') as f:
    reader = reader(f)
    for row in reader:
        col_val = row[col]
        col_values.append(col_val)

# contains only values from column index <col>
print(col_values)
import csv
import collections

col_values = collections.defaultdict(list)
with open('Wierd_stuff.csv', 'rU') as f:
    reader = csv.reader(f)
    # skip field names
    next(reader)
    for row in csv.reader(f):
        for col, value in enumerate(row):
            col_values[col].append(value)

# for each numbered column you want...
col_index = 33  # for example
print(col_values[col_index])

If you know the columns you want in advance, only storing those columns could save you some space...

cols = set(1, 5, 6, 234)

...
        for col, value in enumerate(row):
            if col in cols:
                col_values[col].append(value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM