プリンキピア

第2章準備

2.2.1. Reading the Dataset2.2.1 データセットの読み込み

Comma-separated values (CSV) files are ubiquitous for the storing of tabular (spreadsheet-like) data. In them, each line corresponds to one record and consists of several (comma-separated) fields, e.g., “Albert Einstein,March 14 1879,Ulm,Federal polytechnic school,field of gravitational physics”. To demonstrate how to load CSV files with pandas, we create a CSV file below ../data/house_tiny.csv. This file represents a dataset of homes, where each row corresponds to a distinct home and the columns correspond to the number of rooms (NumRooms), the roof type (RoofType), and the price (Price).
英語のヒント
カンマ区切り値(CSV)ファイルは、表形式の(スプレッドシートのような)データの保存にどこでも使われている。CSVでは、各行が一つのレコードに対応し、いくつかの(カンマで区切られた)フィールドからなる。たとえば「Albert Einstein,March 14 1879,Ulm,Federal polytechnic school,field of gravitational physics」である。pandasでCSVファイルを読み込む方法を示すために、下で../data/house_tiny.csvというCSVファイルを作る。このファイルは家のデータセットを表し、各行が別々の家に対応し、列は部屋数(NumRooms)、屋根の種類(RoofType)、価格(Price)に対応する。
import os

os.makedirs(os.path.join('..', 'data'), exist_ok=True)
data_file = os.path.join('..', 'data', 'house_tiny.csv')
with open(data_file, 'w') as f:
    f.write('''NumRooms,RoofType,Price
NA,NA,127500
2,NA,106000
4,Slate,178100
NA,NA,140000''')
Now let’s import pandas and load the dataset with read_csv.
英語のヒント
では、pandasをインポートし、read_csvでデータセットを読み込もう。
import pandas as pd

data = pd.read_csv(data_file)
print(data)
   NumRooms RoofType   Price
0       NaN      NaN  127500
1       2.0      NaN  106000
2       4.0    Slate  178100
3       NaN      NaN  140000