Home > Software design >  Python: how do I convert all columns except one in a CSV to integers
Python: how do I convert all columns except one in a CSV to integers

Time:09-05

I have CSV files with varying number of columns. The first column is always a string, the other columns are always integers.

The first column is always "name", but the other columns can have different names - so I cannot hardcode the key values for any column except for "name".

Ideally there would be some kind of syntax/function that would allow me to do !"name" to int and then I could put something together.

Here is what I have now, it does not do the conversion to int, it just builds a dictionary.

import csv

persons = []
    database_csv = sys.argv[1]
    with open(database_csv, "r") as database:
            read_csv = csv.DictReader(database)
            for row in read_csv:
                persons.append(row)

I have found solutions to convert all to int, key (for example "name") to int, but I could not find anything that would let me convert everything except "name" to int.

CodePudding user response:

I dont know if you heard about pandas. But you can used the following

import pandas as pd

df = pd.read_csv(database_csv)
persons = df.values.tolist()

CodePudding user response:

Hope this helps ,

import csv

persons = []
with open("database.csv", "r") as database:
    read_csv = csv.DictReader(database)
    for row in read_csv:
        # Type decl does nothing.
        row: dict
        print(row.keys())
        for key in row.keys():
            print(row[key])

CodePudding user response:

Does this work?

import csv


with open(database_csv) as fp:
    csvreader = csv.reader(fp)
    headers = next(csvreader)
    name_idx = headers.index('name')
    rows = [row for row in csvreader]
    rows = [int(value) for value in row for row in rows if row.index(value) != name_idx]
  • Related