データ型の制約

Pythonによるデータクリーニング

Adel Nehme

VP of AI Curriculum, DataCamp

コース概要

dirty_data

Pythonによるデータクリーニング

コース概要

副作用

Pythonによるデータクリーニング

コース概要

clean_data

Pythonによるデータクリーニング

コース概要

clean_data

第1章 - よくあるデータの問題

Pythonによるデータクリーニング

なぜデータをクレンジングする必要があるのですか?

ds_workflow

Pythonによるデータクリーニング

なぜデータをクレンジングする必要があるのですか?

ds_workflow

Pythonによるデータクリーニング

なぜデータをクレンジングする必要があるのですか?

                                                                               **ゴミを入れればゴミが出る**
Pythonによるデータクリーニング

データ型の制約

データ型 例
テキスト データ 名、姓、住所 ...
整数 # 登録者数、# 販売製品数 ...
小数点 温度、為替レート ...
バイナリ 既婚、新規顧客、はい/いいえ、...
日付 注文日、出荷日 ...
カテゴリ一覧 婚姻状況、性別 ...
Pythonのデータ型
str
int
float
bool
datetime
category
Pythonによるデータクリーニング

文字列を整数に変換する

# Import CSV file and output header
sales = pd.read_csv('sales.csv')
sales.head(2)
   SalesOrderID    Revenue    Quantity
0         43659     23153$          12
1         43660      1457$           2
# Get data types of columns
sales.dtypes
SalesOrderID    int64
Revenue         object
Quantity        int64
dtype: object
Pythonによるデータクリーニング

文字列から整数へ

# Get DataFrame information
sales.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 31465 entries, 0 to 31464
Data columns (total 3 columns):
SalesOrderID     31465 non-null int64
Revenue          31465 non-null object
Quantity         31465 non-null int64
dtypes: int64(2), object(1)
memory usage: 737.5+ KB
Pythonによるデータクリーニング

文字列から整数へ

# Print sum of all Revenue column
sales['Revenue'].sum()
'23153$1457$36865$32474$472$27510$16158$5694$6876$40487$807$6893$9153$6895$4216..
# Remove $ from Revenue column
sales['Revenue'] = sales['Revenue'].str.strip('$')
sales['Revenue'] = sales['Revenue'].astype('int')
# Verify that Revenue is now an integer
assert sales['Revenue'].dtype == 'int'
Pythonによるデータクリーニング

アサート文

# This will pass
assert 1+1 == 2
# This will not pass
assert 1+1 == 3
AssertionError                            Traceback (most recent call last)
         assert 1+1 == 3
AssertionError:
Pythonによるデータクリーニング

数値型かカテゴリ型か?

...   marriage_status    ...
...                 3    ...
...                 1    ...
...                 2    ...

0 = 未婚 1 = 既婚 2 = 別居 3 = 離婚

df['marriage_status'].describe()
       marriage_status
...
mean              1.4
std               0.20
min               0.00
50%               1.8 ...
Pythonによるデータクリーニング

数値型かカテゴリ型か?

# Convert to categorical
df["marriage_status"] = df["marriage_status"].astype('category')

df.describe()
        marriage_status
count                 241
unique                4
top                   1
freq                  120
Pythonによるデータクリーニング

お疲れさまでした!

Pythonによるデータクリーニング

Preparing Video For Download...