0
1

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.

Pandasメモ

Last updated at Posted at 2020-07-28

Pythonの学習でPandas関連の内容があった場合は、随時更新していく予定。

Pandas

データ解析を支援する機能を提供するライブラリ


インポート

import pandas as pd

データの取り込み

CSV の読み込み [read_csv]
csv_test_1 = pd.read_csv('hoge.csv')
warking_master = pd.read_csv(path, encoding="SHIFT-JIS")

以下のエラーとなった場合はencoding を設定して対応する
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x93 in position 0: invalid start byte
Excel の読み込み [read_excel]
excel_data = pd.read_excel('hoge.xlsx')

データの結合(ユニオン)

データの縦結合 [concat]
csv_test_2 = pd.read_csv('hoge_2.csv')
csv_test = pd.concat([csv_test_1 , csv_test_2], ignore_index=True)
csv_test.head()
データの結合 LEFT JOIN [merge]

・結合する両テーブルの項目名が同じ場合。on="id"を条件に結合。

結合後テーブル = pd.merge(テーブル1, テーブル2, on="結合項目", how="方法")

join_data = pd.merge(a_data, b_data[["id", "date", "customer"]], on="id", how="left")
join_data.head()

・結合する両テーブルの項目名が異なる場合。left_on="customer_name", right_on="顧客名""を条件に結合。

pd.merge(a_data, b_data, left_on="customer_name", right_on="顧客名", how="left")

データの確認

ユニークなデータの取得 [pd.unique(データ)]
pd.unique(test_data.item_name))
len(pd.unique(test_data.item_name))) # ユニークデータの個数

日付の操作

a列の値をdatetime型に変換 [to_datetime()]
test_data["a"] = pd.to_datetime(test_data["a"])
日付の抽出 [dt]
日付のフォーマット [dt.strftime("%Y%m")]
time_data["payment_month"] = time_data["payment_date"].dt.strftime("%Y%m")

ピボットテーブル

ピボットテーブルを作成する [pd.pivot_table]
pd.pivot_table(test_data, index='item_name', columns='payment_month', values=['price', 'quantity'], aggfunc='sum')

・pivot_table 概要
index : 行を指定
columns: 列を指定
values : 集計する値を指定
aggfunc: 集計方法を指定


Pandasの内容ではないので後別だしで整理

データの表示

表示 [print]
print(len(test_data))  # データ件数を表示する
データの先頭の5行を表示 [head]
csv_test_1.head()
データの列を指定して、先頭の5行を表示 [head]
csv_test_1["列名"].head()

データの操作

.loc関数でデータを抽出する [.loc(条件, 取得する列)]
res = test_data.loc[flg_is_null, "item_name"]

データ列の作成

aとbを掛け合わせた値を、追加列の new に設定する
test_data["new"] = test_data["a"] * test_data["b"]

データの計算

a列を合計する [列.sum()]
test_data["a"].sum()
指定したグループで集計 [groupby("列").sum("列")]
test_data.groupby("create_date").sum()["price"]
指定したグループで集計(複数指定) [groupby("列").sum("列")]
test_data.groupby(["create_date", "item_name"]).sum()[["price", "quantity"]]

データの比較

a列の合計とb列の合計を比較し、結果をTRUE/FALSEで表示する
test_data["a"].sum() == test_data["b"].sum()
欠損値の確認、列ごとにnullをTRUE/FALSEで返し、sumで合計している
test_data.isnull().sum()
欠損値の確認 列ごとに欠損値の有無をTRUE/FALSEで返す
test_data.isnull().any(axis=0)
各種統計量の出力 [describe()]
test_data.describe()
指定した列の最大、最小値 [max(), min()]
test_data["create_date"].min()
test_data["create_date"].max()
データ型の確認 [dtypes]
test_data.dtypes

・describe() で、以下の各種統計量を表示できる。
 データ件数(count)、平均値(mean)、標準偏差(std)、最小値(min)、四分位数(25%,75%)、中央値(50%)、最大値(max)

NetworkX

ネットワーク可視化に有用なライブラリ

簡単な利用

頂点(nodeA,nodeB,nodeC)とそれをつなぐ辺を設定し、それを matplotlib の show で表示している。

import networkx as nx
import matplotlib.pyplot as plt

# グラフオブジェクトの作成
G=nx.Graph()

# 頂点の設定
G.add_node("nodeA")
G.add_node("nodeB")
G.add_node("nodeC")

# 辺の設定
G.add_edge("nodeA","nodeB")
G.add_edge("nodeA","nodeC")
G.add_edge("nodeB","nodeC")

# 座標の設定
pos={}
pos["nodeA"]=(0,0)
pos["nodeB"]=(1,1)
pos["nodeC"]=(0,1)

# 描画
nx.draw(G,pos)

# 表示
plt.show()

最適化計算ライブラリ

・anaconda で pulp をインストールを選択できない場合。コマンドでインストールを実行する。

・ortoolpy は conda コマンドではなく、pip コマンドでのインストールで実行する。

conda install -c conda-forge pulp

pip install ortoolpy

作業メモ
・データのクレンジング

データ加工:Pandas
可視化:Matplotlib
機械学習:scikit-learn

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?