2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonテクニック csvやexcelデータの読み込み read_csv/sas7bdat/connect

Last updated at Posted at 2020-07-24

pythonによるcsv/excel/sasデータの読み込みとデータベースの接続方法

csvの読み込みならread_csv
excelの読み込みならread_excel
SASデータセットの読み込みならsas7bdatやpandasのread_sas
DBへの接続ならsqlite3.connectなど

準備

import pandas as pd
import dask
import dask.dataframe as dd
from dask.delayed import delayed
import sqlite3
from sas7bdat import SAS7BDAT

csvの読み込み read_csv

Data = pd.read_csv( "パス/ファイル名.csv" )
Data = dd.read_csv( "パス/ファイル名.csv" ).compute()

Daskの方が処理速度はやいので、大容量データの場合はDaskの方がいいかも

列名や型を指定する場合(データの1行目に列名あるならheader = 0で1行目無視)

FilePass = "パス/ファイル名.csv"
FilePass = "./data/test.csv"
name1 = "列名1", "列名2" , "列名3" , ...
type1 = { "列名1":"str" , "列名2":"int" , "列名3":"float" , ... }
Data = dd.read_csv( FilePass, encoding = "cp932", header = 0 ,names = ( name1 ), dtype = type1 ).compute()
test_csv.PNG yomikomi.PNG

excelの読み込み read_excel

Data = pd.read_excel( "パス/ファイル名.xlsx" ,sheet_name = "シート名" )

csvと同様、列名の指定なども可

Daskにread_excelなかったが、無理やりやるなら

aaaaa = dask.delayed(pd.read_excel)( "パス/ファイル名.xlsx" ,sheet_name = "シート名" )
Data = dd.from_delayed( aaaaa ).compute()

SASデータセットの読み込み sas7bdat/read_sas

# sas7bdat
Data = SAS7BDAT( "パス/ファイル名.sas7bdat" , encoding = "cp932" ).to_data_frame()
# pandasで読み込む場合(日本語入ってると、エラーにはならないが正しく読み込めない)
Data = pd.read_sas( "パス/ファイル名.sas7bdat" , format = "sas7bdat" )

DB接続(SQLite3)

# データベース接続
conn = sqlite3.connect( "パス/db名.db" )
# データベース閉じる
conn.close()

https://pandas.pydata.org/docs/user_guide/io.html#csv-text-files
https://pandas.pydata.org/docs/user_guide/io.html#excel-files
https://examples.dask.org/dataframes/01-data-access.html
https://docs.python.org/ja/3/library/sqlite3.html

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?