資料型別限制

用 Python 進行資料清理

Adel Nehme

VP of AI Curriculum, DataCamp

課程大綱

dirty_data

用 Python 進行資料清理

課程大綱

side effects

用 Python 進行資料清理

課程大綱

clean_data

用 Python 進行資料清理

課程大綱

clean_data

第 1 章-常見資料問題

用 Python 進行資料清理

為何要清理資料?

ds_workflow

用 Python 進行資料清理

為何要清理資料?

ds_workflow

用 Python 進行資料清理

為何要清理資料?

                                                                                   Garbage in Garbage out

用 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 進行資料清理

assert 陳述式

# 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...