2016年11月21日月曜日

PandasでSeriesオブジェクトとDataFrameオブジェクトを作る

Pandasのデータ構造


Pandasでは、データの入出力、抽出、並べ替えなどの処理をすることができる。
Pandasでは、主に以下の2つのデータ構造が定義されている。
- Series:ラベル付きの1次元配列
- DataFrame:ラベル付きの2次元配列。スプレッドシートやデータベースのテーブルや辞書のようなもの。

pandas.Series()


まず、Seriesオブジェクトを作ってみる

import pandas as  pd

s = pd.Series([10 , 4, 7, 34, 6])
s

#結果
#0    10
#1     4
#2     7
#3    34
#4     6
#dtype: int64

date_range()を使って日付をインデックスにすることもできる。

import pandas as  pd

s = pd.Series([10 , 4, 7, 34, 6], index=date_range('1/1/2016', periods=5))
s

#結果
#2016-01-01    10
#2016-01-02     4
#2016-01-03     7
#2016-01-04    34
#2016-01-05     6
#Freq: D, dtype: int64

pandas.DataFrame()


次に、DataFrameオブジェクトを作ってみる。
適当に果物屋さんの売上のようなものでやってみましょうか。

import pandas as  pd

fruit_sales = {'Fruits': ['Apple', 'Orange', 'Grape', 'Peach', 'Lemon'],
                'Price': [100, 120, 150, 130, 90],
                'Sold': [14, 40, 23, 25, 12]}

df = pd.DataFrame(fruit_sales)
df

#結果
#   Fruits  Price  Sold
#0   Apple    100    14
#1  Orange    120    40
#2   Grape    150    23
#3   Peach    130    25
#4   Lemon     90    12

もちろん、インデックスを指定することもできる。
set_index()を使って、Fruitsをインデックスにしてみましょう。

import pandas as  pd

fruit_sales = {'Fruits': ['Apple', 'Orange', 'Grape', 'Peach', 'Lemon'],
                'Price': [100, 120, 150, 130, 90],
                'Sold': [14, 40, 23, 25, 12]}

df = pd.DataFrame(fruit_sales)
df.set_index('Fruits', inplace=True)
df

#結果
#        Price  Sold
#Fruits             
#Apple     100    14
#Orange    120    40
#Grape     150    23
#Peach     130    25
#Lemon      90    12

指定したカラムだけを抽出することもできる。

df = pd.DataFrame(fruit_sales)
df['Price']
#df.Price ←このようにドットでつなげても同じ結果が得られる

#結果
#0    100
#1    120
#2    150
#3    130
#4     90
#Name: Price, dtype: int64

複数のカラムを抽出することもできる。

df = pd.DataFrame(fruit_sales)
df[['Price', 'Sold']]

#結果
#   Price  Sold
#0    100    14
#1    120    40
#2    150    23
#3    130    25
#4     90    12

1次元配列(Series)であれば、tolist()を使って、指定したカラムの値をリストにすることが可能。

df = pd.DataFrame(fruit_sales)
df.Price.tolist()

#結果
#[100, 120, 150, 130, 90]

しかし、以下のように2次元配列(DataFrame)にはtolist()を使うことはできない。
DataFrameオブジェクトにはtolistという属性はないと怒られます。

df = pd.DataFrame(fruit_sales)
print(df[['Price', 'Sold']].tolist())

AttributeError: 'DataFrame' object has no attribute 'tolist'

こういった多次元のデータセットを扱うにはNumpyを使うのがいい。Numpyをインポートして、np.array()でN次元配列を扱うことができる。

import numpy as np

df = pd.DataFrame(fruit_sales)
print(np.array(df[['Price', 'Sold']]))

#結果
#[[100  14]
 #[120  40]
 #[150  23]
 #[130  25]
 #[ 90  12]]

0 コメント:

コメントを投稿