python「pandas」の使い方

スポンサーリンク

pandasとは?

Python用のデータ分析ライブラリ。
エクセルのような表形式のデータを簡単に取り扱うことができる。
統計量の計算、データの可視化もできる。

import numpy as np
import pandas as pd

Seriesクラス
1次元のデータ構造を持つクラス

DataFrameクラス
2次元のデータ構造を持つクラス

Seriesクラス

series = pd.Series(data=[1, 2, 3, 4, 5], index=['A', 'B', 'C', 'D', 'E'])
series

A    1
B    2
C    3
D    4
E    5
dtype: int64

numpyの配列やリストを指定

array = np.arange(1, 11) # numpy.ndarray
array
>array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

index = 'a b c d e f g h i j'.split() # list
index
>['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

series = pd.Series(data=array, index=index)
series

a     1
b     2
c     3
d     4
e     5
f     6
g     7
h     8
i     9
j    10
dtype: int64

データ抽出:locメソッド

locメソッド:インデックスを指定

series.loc['a']
>1

series.loc['a':'d']
a    1
b    2
c    3
d    4
dtype: int64

series.loc[['b', 'd']]
b    2
d    4
dtype: int64

ilocメソッド:データ位置を番号で指定

series = pd.Series(data=[1, 2, 8, 4, 5], index=['A', 'B', 'C', 'D', 'E'])
series.iloc[2]
>8

series.iloc[:3]
A    1
B    2
C    8
dtype: int64

DataFrame データ分析


df = pd.DataFrame(data=[[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df

   0  1  2
0  1  2  3
1  4  5  6
2  7  8  9

df = pd.DataFrame(data=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=['A','B','C'], columns=['C1','C2','C3'])
df

   C1  C2  C3
A   1   2   3
B   4   5   6
C   7   8   9

DataFrame データ分析 学習用データ

データ分析 学習用データをインポートしてデータフレームに。
headで上の5行だけを表示。

from sklearn.datasets import load_iris

iris = load_iris()
iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
iris_df.head()

ファイルの読み込み

CSV, Excel, HTMLなどのデータを読み込み可能。

read_csv()
read_excel()
read_html()

df = pd.read_csv('train.csv', nrows=500) #500行読む
df.head()

describe() 各種統計量確認

describe()
count: 要素の個数
unique: ユニークな(一意な)値の要素の個数
top: 最頻値(mode)
freq: 最頻値の頻度(出現回数)
mean: 算術平均
std: 標準偏差
min: 最小値
max: 最大値
50%: 中央値(median)
25%, 75%: 1/4分位数、3/4分位数

from sklearn.datasets import load_iris
iris = load_iris()
iris_df = pd.DataFrame(data=iris.data, columns=iris.feature_names)  
iris_df.describe()

info() データ数と型を確認

RangeIndex: 150 entries, 0 to 149
Data columns (total 4 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   sepal length (cm)  150 non-null    float64
 1   sepal width (cm)   150 non-null    float64
 2   petal length (cm)  150 non-null    float64
 3   petal width (cm)   150 non-null    float64
dtypes: float64(4)
memory usage: 4.8 KB

python
スポンサーリンク
のんびりブログ

コメント

タイトルとURLをコピーしました