<< home

Pandasの基本

pandasはPythonのデータ分析ライブラリであり、表形式のデータを効率的に扱うことができます。本章では、pandasの基本的なデータ構造であるSeriesDataFrameについて解説します。

1. Seriesの基本

Seriesは1次元のデータ構造で、インデックスと値を持ちます。

import pandas as pd # リストからSeriesを作成 s = pd.Series([10, 20, 30, 40]) print(s)

出力例:

0 10 1 20 2 30 3 40 dtype: int64

インデックスを指定することもできます。

s = pd.Series([10, 20, 30, 40], index=['a', 'b', 'c', 'd']) print(s)
a 10 b 20 c 30 d 40 dtype: int64

個別の要素にアクセスできます。

print(s['b']) # 20

2. DataFrameの基本

DataFrameは表形式のデータ構造で、行と列を持ちます。

2.1 DataFrameの作成

リストや辞書からDataFrameを作成できます。

# 辞書からDataFrameを作成 data = {'名前': ['Alice', 'Bob', 'Charlie'], '年齢': [25, 30, 35], '得点': [85, 90, 95]} df = pd.DataFrame(data) print(df)
名前 年齢 得点 0 Alice 25 85 1 Bob 30 90 2 Charlie 35 95

2.2 データの取得

特定の列を取得:

print(df['名前'])

特定の行を取得:

print(df.loc[1]) # インデックスで指定

条件でデータをフィルタリング:

print(df[df['年齢'] > 25])

2.3 データの追加と削除

新しい列を追加:

df['身長'] = [160, 175, 180] print(df)

列を削除:

df = df.drop(columns=['得点']) print(df)

2.4 基本的な統計情報の取得

pandasには便利な統計関数が用意されています。

print(df.describe()) # 数値データの統計情報
print(df.info()) # データの概要

3. まとめ

pandasを活用することで、データ分析がより簡単に行えます。



<< home