-1

I have a csv file. I need to iterate over each row accessing specific fields per row and use that data in the next stage.

Was thinking of using some numpy load csv method.

404Hero
  • 1
  • 1
  • 1
    It depends on how you want to manipulate the csv. For data analysis, a popular module is [pandas](https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html). – Marcelo Paco Mar 28 '23 at 16:54

3 Answers3

0

This should work.

pip install csv
with open('my-csv-file.csv', newline='') as csvFile:
    csvData = csv.reader(csvFile, delimiter=',', quotechar='|')
    for row in csvData:
        print(', '.join(row))
centralhubb.com
  • 2,705
  • 19
  • 17
0

Loading CSV using NumPy

Numpy does offer a functionality for this. It's called np.loadtxt.


import numpy as np
 
# using loadtxt()
arr = np.loadtxt("sample_data.csv",
                 delimiter=",", dtype=str)
display(arr)

Loading CSV into an array using Python's csv library

Python offers a csv library for this as well.

import csv
with open('sample_data.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        print(', '.join(row))

Loading CSV using built-in Python

Alternatively you don't actually need to use a third-party library. CSV is simply a text file with comma-separated values. Knowing this you can use the Python built in method to parse it.

with open("data.csv") as data:
    for line in data:
        items = [item for item in line.split(",")]
        print(items)
0

The most popular library for tabular data handling is pandas

Sample data -

csv = '''"Header1", "Header2"
"Replace", 100
"string", 200
"with", 300
"file location", 400
"or url", 500'''

Code to only import one column -

import pandas
data = pandas.read_csv(csv, headers=["header1"]

printing data gives a table like

|"Header1"       |
|----------------|
|"Replace"       |
|"string"        |
|"with"          |
|"file location" |
|"or url"        |

More info here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

ciaran haines
  • 294
  • 1
  • 11