How to read csv containing only integers in Python

I saw a person who is struggling to write a double loop by himself to read csv like the following in Python, so I will summarize four typical reading methods.

sample.csv


1,2,3
4,5,6
7,8,9
10,11,12

In addition, StringIO is used here to emulate file reading, but when actually using it, please read it as an open function or a character string of the file name as appropriate.

Use csv module

How to use the standard Python library CSV. There may be a merit that it works only with the standard library, but in reality it is unlikely that you will handle data containing only numerical values as a double list.

Note that each element is still a string, so we put map (int, row) in between to convert it as a number.

from io import StringIO
import csv
s = """1,2,3
4,5,6
7,8,9
10,11,12"""

with StringIO(s) as csvfile:
    csvreader = csv.reader(csvfile)
    rows = []
    for row in csvreader:
        rows.append(list(map(int, row)))

#or list comprehension
with StringIO(s) as csvfile:
    csvreader = csv.reader(csvfile)
    rows = [list(map(int, row)) for row in csvreader]

import numpy as np
arr = np.array(rows)

numpy

loadtxt and [genfromtxt](https://numpy.org/doc/stable/reference/generated /numpy.genfromtxt.html?highlight=genfromtxt#numpy.genfromtxt). Both have similar interfaces, but genfromtxt is a little more sophisticated because it can replace missing values.

numpy.loadtxt

from io import StringIO
import numpy as np

s = """1,2,3
4,5,6
7,8,9
10,11,12"""

with StringIO(s) as csvfile:
    arr = np.loadtxt(csvfile, delimiter=",", dtype=int)

numpy.genfromtxt

from io import StringIO
import numpy as np

s = """1,2,3
4,5,6
7,8,9
10,11,12"""

with StringIO(s) as csvfile:
    arr = np.genfromtxt(csvfile, delimiter=",", dtype=int)

pandas

np.genfromtxt can also handle missing values, but pandas may be easier to find information.

pandas.read_csv

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

This time, it is treated as csv without header, so put the option of header = None.

from io import StringIO
import pandas as pd

s = """1,2,3
4,5,6
7,8,9
10,11,12"""

with StringIO(s) as csvfile:
    df = pd.read_csv(csvfile, header=None, dtype=int)
arr = df.values

Please let me know if there is another convenient method.

Recommended Posts

How to read csv containing only integers in Python
How to read CSV files in Pandas
How to read a CSV file with Python 2/3
How to develop in Python
[Python] How to do PCA in Python
How to collect images in Python
How to use SQLite in Python
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
How to handle Japanese in Python
[Python] How to convert db file to csv
[Introduction to Python] How to use class in Python?
How to access environment variables in Python
How to dynamically define variables in Python
How to do R chartr () in Python
How to convert csv to tsv in CLI
[Itertools.permutations] How to put permutations in Python
How to work with BigQuery in Python
How to display multiplication table in python
How to extract polygon area in Python
How to check opencv version in python
Read Python csv and export to txt
How to switch python versions in cloud9
How to adjust image contrast in Python
How to use __slots__ in Python class
How to dynamically zero pad in Python
Csv in python
How to use regular expressions in Python
How to display Hello world in python
How to use is and == in Python
How to write Ruby to_s in Python
[Python] How to read a csv file (read_csv method of pandas module)
How to use the C library in Python
How to receive command line arguments in Python
[REAPER] How to play with Reascript in Python
How to clear tuples in a list (Python)
How to generate permutations in Python and C ++
How to embed a variable in a python string
How to implement Discord Slash Command in Python
Summary of how to import files in Python 3
How to simplify restricted polynomial fit in python
How to use Python Image Library in python3 series
How to implement shared memory in Python (mmap.mmap)
How to create a JSON file in Python
[Python] How to read excel file with pandas
Summary of how to use MNIST in Python
Convert UTF-8 CSV files to read in Excel
How to notify a Discord channel in Python
How to get the files in the [Python] folder
How to use tkinter with python in pyenv
How to run Leap Motion in non-Apple Python
How to read time series data in PyTorch
[Python] How to draw a histogram in Matplotlib
How to output "Ketsumaimo" as standard output in Python
How to handle datetime type in python sqlite3
How to read a file in a different directory
How to make Python Interpreter changes in Pycharm
How to plot autocorrelation and partial autocorrelation in python
How to remove duplicate elements in Python3 list