pandas の基礎知識¶
本資料では、時間割編成問題に限らず、あらゆる表形式データの処理に役立つ pandas の基本操作を段階的に学ぶ。各節には解説と練習問題が含まれ、最後には補足として機能別操作一覧も掲載している。
In [1]:
import pandas as pd
data = {'名前': ['田中', '佐藤', '鈴木'], '年齢': [25, 30, 22]}
df = pd.DataFrame(data)
print(type(df)) # DataFrame 型
print(type(df['名前'])) # Series 型
<class 'pandas.core.frame.DataFrame'> <class 'pandas.core.series.Series'>
In [2]:
df.to_csv('example.csv', index=False)
df2 = pd.read_csv('example.csv', encoding='utf-8')
print(df2)
名前 年齢 0 田中 25 1 佐藤 30 2 鈴木 22
In [3]:
print(df.head(2))
print(df.columns)
名前 年齢 0 田中 25 1 佐藤 30 Index(['名前', '年齢'], dtype='object')
In [4]:
print(df['名前'])
print(df[['名前', '年齢']])
0 田中 1 佐藤 2 鈴木 Name: 名前, dtype: object 名前 年齢 0 田中 25 1 佐藤 30 2 鈴木 22
In [5]:
df[df['年齢'] > 25]
Out[5]:
| 名前 | 年齢 | |
|---|---|---|
| 1 | 佐藤 | 30 |
In [6]:
df['年齢カテゴリ'] = ['若手', 'ベテラン', '若手']
df
Out[6]:
| 名前 | 年齢 | 年齢カテゴリ | |
|---|---|---|---|
| 0 | 田中 | 25 | 若手 |
| 1 | 佐藤 | 30 | ベテラン |
| 2 | 鈴木 | 22 | 若手 |
In [7]:
df['部署'] = ['A', 'B', 'A']
print(df)
print(df['名前'].value_counts())
print(df.groupby('部署')['年齢'].mean())
名前 年齢 年齢カテゴリ 部署 0 田中 25 若手 A 1 佐藤 30 ベテラン B 2 鈴木 22 若手 A 名前 田中 1 佐藤 1 鈴木 1 Name: count, dtype: int64 部署 A 23.5 B 30.0 Name: 年齢, dtype: float64
In [8]:
data = {'名前': ['田中', '佐藤', '鈴木'], '年齢': [25, None, 22]}
df = pd.DataFrame(data)
print(df.isnull())
print(df['年齢'].fillna(0))
名前 年齢 0 False False 1 False True 2 False False 0 25.0 1 0.0 2 22.0 Name: 年齢, dtype: float64
In [9]:
data = {'名前': ['田中', '佐藤', '田中'], '年齢': [25, 30, 25]}
df = pd.DataFrame(data)
print(df)
print(df.sort_values(by='年齢', ascending=False))
print(df.drop_duplicates())
名前 年齢 0 田中 25 1 佐藤 30 2 田中 25 名前 年齢 1 佐藤 30 0 田中 25 2 田中 25 名前 年齢 0 田中 25 1 佐藤 30
In [10]:
def age_category(age):
return '若手' if age < 30 else 'ベテラン'
print(df)
df['区分'] = df['年齢'].apply(age_category)
print(df)
名前 年齢 0 田中 25 1 佐藤 30 2 田中 25 名前 年齢 区分 0 田中 25 若手 1 佐藤 30 ベテラン 2 田中 25 若手