資料型別與資料合併

使用 pandas 分析行銷活動

Jill Rosok

Data Scientist

常見資料型別

  • 字串(object)
  • 數值(float、integer)
  • 布林值(True、False)
  • 日期
使用 pandas 分析行銷活動

欄位的資料型別

# Print a data type of a single column
print(marketing['converted'].dtype)
dtype('object')
使用 pandas 分析行銷活動

變更欄位的資料型別

# Change the data type of a column
marketing['converted'] = marketing['converted']\
                          .astype('bool')

print(marketing['converted'].dtype)
dtype('bool')
使用 pandas 分析行銷活動

建立新的布林欄位

marketing['is_house_ads'] = np.where(
    marketing['marketing_channel'] == 'House Ads', 
    True, False
)

print(marketing.is_house_ads.head(3))
0    True
1    False
2    True
Name: is_house_ads, dtype: bool
使用 pandas 分析行銷活動

將值對應到既有欄位

channel_dict = {"House Ads": 1, "Instagram": 2, 
                "Facebook": 3, "Email": 4, "Push": 5}

marketing['channel_code'] = marketing['marketing_channel']\ .map(channel_dict) print(marketing['channel_code'].head(3))
0    1
1    1
2    1
Name: channel_code, dtype: int64
使用 pandas 分析行銷活動

日期欄位

# Read date columns using parse_dates
marketing = pd.read_csv('marketing.csv', 
                        parse_dates=['date_served', 
                                     'date_subscribed', 
                                     'date_canceled'])

# Or
# Convert already existing column to datetime column
marketing['date_served'] = pd.to_datetime(
    marketing['date_served']
)
使用 pandas 分析行銷活動

日期欄位

# Or convert each column individually
# Convert already existing column to datetime column
marketing['date_served'] = pd.to_datetime(
    marketing['date_served']
)
使用 pandas 分析行銷活動

日期欄位

marketing['day_served'] = marketing['date_served']\
                       .dt.dayofweek
使用 pandas 分析行銷活動

一起來練習吧!

使用 pandas 分析行銷活動

Preparing Video For Download...