Read Python csv file

Various pandas commands

data2.csv


Nafn,Sysla,ID,Starfsgrein,Aldur,Kynlíf,
Dom,Árnessýsla,00027861s,Embættismaður,30,karlkyns
Ola,Gullbringusýsla,00033014s,bankastjóri,26,kona
Qiv,Vestur-Skaftafellssýsla,00087295j,Sjómaður,47,karlkyns
Uba,Suður-Múlasýsla,00043765e,Bóndi,66,kona
Yhe,Norður-Múlasýsla ,00021559e,Fréttaritari,35,kona

What you are doing in the example below -Specify index with read_csv (0, 1, 2, ... if not specified) -Output by specifying a column · Get row · Get column ・ Slice the line -Get the value by specifying the row / column name -Get the value by specifying the row index and column index

import pandas


csv_input = pandas.read_csv("data2.csv")
print('///csv_input///\n')
print(csv_input)
print('---------------')
print("///csv_input['ID']///\n")
print(csv_input['ID'])
print('---------------')
print('///csv_input.index.values///\n')
print(csv_input.index.values)
print('---------------')
print('///csv_input.columns.values///\n')
print(csv_input.columns.values)
print('---------------')
print('///csv_input.iloc[2, 3]///\n')
print(csv_input.iloc[2, 3])
print('---------------')
print("///csv_input.loc[2, 'Starfsgrein']///\n")
print(csv_input.loc[2, 'Starfsgrein'])
print('---------------')
print("///csv_input.loc[2:4, 'Starfssgrein']///\n")
print(csv_input.loc[2:4, 'Starfsgrein'])
print('---------------')
print('///csv_input.iloc[2:4, 3]///\n')
print(csv_input.iloc[2:4, 3])
print('---------------')

print('\n***************\n')

csv_input = pandas.read_csv("data2.csv", index_col=0)
print('///csv_input///\n')
print(csv_input)
print('---------------')
print("///csv_input['ID']///\n")
print(csv_input['ID'])
print('---------------')
print('///csv_input.index.values///\n')
print(csv_input.index.values)
print('---------------')
print('///csv_input.columns.values///\n')
print(csv_input.columns.values)
print('---------------')
print('///csv_input.iloc[2, 2]///\n')
print(csv_input.iloc[2, 2])
print('---------------')
print("///csv_input.loc['Qiv', 'Starfsgrein']///\n")
print(csv_input.loc['Qiv', 'Starfsgrein'])
print('---------------')
print("///csv_input.loc['Qiv':'Uba', 'Starfsgrein']///\n")
print(csv_input.loc['Qiv':'Uba', 'Starfsgrein'])
print('---------------')
print('///csv_input.iloc[2:4, 2]///\n')
print(csv_input.iloc[2:4, 2])

user_name@DESKTOP-3128479:/mnt/c/Users/TEST_USER/MyShell$ python3 pand_test.py
///csv_input///

  Nafn                    Sysla         ID    Starfsgrein  Aldur    Kynlíf
0  Dom               Árnessýsla  00027861s  Embættismaður     30  karlkyns
1  Ola          Gullbringusýsla  00033014s    bankastjóri     26      kona
2  Qiv  Vestur-Skaftafellssýsla  00087295j       Sjómaður     47  karlkyns
3  Uba          Suður-Múlasýsla  00043765e          Bóndi     66      kona
4  Yhe        Norður-Múlasýsla   00021559e   Fréttaritari     35      kona
---------------
///csv_input['ID']///

0    00027861s
1    00033014s
2    00087295j
3    00043765e
4    00021559e
Name: ID, dtype: object
---------------
///csv_input.index.values///

[0 1 2 3 4]
---------------
///csv_input.columns.values///

['Nafn' 'Sysla' 'ID' 'Starfsgrein' 'Aldur' 'Kynlíf']
---------------
///csv_input.iloc[2, 3]///

Sjómaður
---------------
///csv_input.loc[2, 'Starfsgrein']///

Sjómaður
---------------
///csv_input.loc[2:4, 'Starfssgrein']///

2        Sjómaður
3           Bóndi
4    Fréttaritari
Name: Starfsgrein, dtype: object
---------------
///csv_input.iloc[2:4, 3]///

2    Sjómaður
3       Bóndi
Name: Starfsgrein, dtype: object
---------------

***************

///csv_input///

                        Sysla         ID    Starfsgrein  Aldur    Kynlíf
Nafn
Dom                Árnessýsla  00027861s  Embættismaður     30  karlkyns
Ola           Gullbringusýsla  00033014s    bankastjóri     26      kona
Qiv   Vestur-Skaftafellssýsla  00087295j       Sjómaður     47  karlkyns
Uba           Suður-Múlasýsla  00043765e          Bóndi     66      kona
Yhe         Norður-Múlasýsla   00021559e   Fréttaritari     35      kona
---------------
///csv_input['ID']///

Nafn
Dom    00027861s
Ola    00033014s
Qiv    00087295j
Uba    00043765e
Yhe    00021559e
Name: ID, dtype: object
---------------
///csv_input.index.values///

['Dom' 'Ola' 'Qiv' 'Uba' 'Yhe']
---------------
///csv_input.columns.values///

['Sysla' 'ID' 'Starfsgrein' 'Aldur' 'Kynlíf']
---------------
///csv_input.iloc[2, 2]///

Sjómaður
---------------
///csv_input.loc['Qiv', 'Starfsgrein']///

Sjómaður
---------------
///csv_input.loc['Qiv':'Uba', 'Starfsgrein']///

Nafn
Qiv    Sjómaður
Uba       Bóndi
Name: Starfsgrein, dtype: object
---------------
///csv_input.iloc[2:4, 2]///

Nafn
Qiv    Sjómaður
Uba       Bóndi
Name: Starfsgrein, dtype: object

Convert csv file to dictionary

Use the DictReader function.

import csv


def get_data_csv(path, mode):
    list = []
    with open(path, mode) as f:
        dict_data = csv.DictReader(f)
        for dict in dict_data:
            list.append(dict)
    return list


if __name__ == "__main__":
    path = 'data2.csv'
    mode = "r"
    list = get_data_csv(path, mode)
    for dict in list:
        print(dict)
user_name@DESKTOP-3128479:/mnt/c/Users/TEST_USER/MyShell$ python3 get_csv.py
{'Nafn': 'Dom', 'Sysla': 'Árnessýsla', 'ID': '00027861s', 'Starfsgrein': 'Embættismaður', 'Aldur': '30', 'Kynlíf': 'karlkyns'}
{'Nafn': 'Ola', 'Sysla': 'Gullbringusýsla', 'ID': '00033014s', 'Starfsgrein': 'bankastjóri', 'Aldur': '26', 'Kynlíf': 'kona'}
{'Nafn': 'Qiv', 'Sysla': 'Vestur-Skaftafellssýsla', 'ID': '00087295j', 'Starfsgrein': 'Sjómaður', 'Aldur': '47', 'Kynlíf': 'karlkyns'}
{'Nafn': 'Uba', 'Sysla': 'Suður-Múlasýsla', 'ID': '00043765e', 'Starfsgrein': 'Bóndi', 'Aldur': '66', 'Kynlíf': 'kona'}
{'Nafn': 'Yhe', 'Sysla': 'Norður-Múlasýsla ', 'ID': '00021559e', 'Starfsgrein': 'Fréttaritari', 'Aldur': '35', 'Kynlíf': 'kona'}

Convert csv file to list

Use the reader function.

import csv


def get_data_csv(path, mode):
    list = []
    with open(path, mode) as f:
        data = csv.reader(f)
        for row in data:
            list.append(row)
    return list


if __name__ == "__main__":
    path = 'data2.csv'
    mode = "r"
    list = get_data_csv(path, mode)
    for element in list:
        print(element)
user_name@DESKTOP-3128479:/mnt/c/Users/TEST_USER/MyShell$ python3 get_csv.py
['Nafn', 'Sysla', 'ID', 'Starfsgrein', 'Aldur', 'Kynlíf']
['Dom', 'Árnessýsla', '00027861s', 'Embættismaður', '30', 'karlkyns']
['Ola', 'Gullbringusýsla', '00033014s', 'bankastjóri', '26', 'kona']
['Qiv', 'Vestur-Skaftafellssýsla', '00087295j', 'Sjómaður', '47', 'karlkyns']
['Uba', 'Suður-Múlasýsla', '00043765e', 'Bóndi', '66', 'kona']
['Yhe', 'Norður-Múlasýsla ', '00021559e', 'Fréttaritari', '35', 'kona']

Reference URL

https://note.nkmk.me/python-pandas-at-iat-loc-iloc/

Recommended Posts

Read Python csv file
Read CSV file: pandas
Read CSV file with python (Download & parse CSV file)
Read and write csv file
Read csv with python pandas
Read file
Download csv file with python
Output to csv file with Python
Script python file
[Python] Read the csv file and display the figure with matplotlib
Python file processing
Csv in python
[python] Read data
[Python] How to convert db file to csv
[Python] Convert csv file delimiters to tab delimiters
Read the file line by line in Python
Read the file line by line in Python
Read Python csv and export to txt
[python] Read html file and practice scraping
[Python] Read the specified line in the file
[Automation] Read mail (msg file) with Python
Read DXF in python
[Python] File / directory operations
[Note] File reading ~ Python ~
File processing in Python
Read and format a csv file mixed with comma tabs with Python pandas
Read a file containing garbled lines in Python
Read Python csv data with Pandas ⇒ Graph with Matplotlib
Read JSON with Python and output as CSV
Automatically execute python file
Writing logs to CSV file (Python, C language)
Read table data in PDF file with Python
File operations in Python
File read overhead measurement
[Python] How to read a csv file (read_csv method of pandas module)
Transpose CSV file in Python Part 2: Performance measurement
Read CSV file with Python and convert it to DataFrame as it is
Csv tinkering with python
Read line by line from a file with Python
python external file reading
[Python] Reading CSV files
[Python] Read From Stdin
Speed evaluation of CSV file output in Python
Various ways to read the last line of a csv file in Python
Template of python script to read the contents of the file
Collectively register data in Firestore using csv file in Python
I tried to touch the CSV file with Python
Read the xml file by referring to the Python tutorial
Read QR code from image file with Python (Mac)
Read json file with Python, format it, and output json
Python script to create a JSON file from a CSV file
Python hand play (get column names from CSV file)
How to read csv containing only integers in Python
Summary of python file operations
Draw netCDF file with python
Read Euler's formula in Python
Read and write a file
Read Namespace-specified XML in Python
Read Outlook emails in Python
Write to csv with Python
AHC task (1) Reading CSV file