数据类型与数据合并

使用 pandas 分析营销活动

Jill Rosok

Data Scientist

常见数据类型

  • 字符串(object)
  • 数值(float、integer)
  • 布尔值(True、False)
  • 日期
使用 pandas 分析营销活动

列的数据类型

# 打印单列的数据类型
print(marketing['converted'].dtype)
dtype('object')
使用 pandas 分析营销活动

更改列的数据类型

# 更改列的数据类型
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 分析营销活动

日期列

# 使用 parse_dates 读取日期列
marketing = pd.read_csv('marketing.csv', 
                        parse_dates=['date_served', 
                                     'date_subscribed', 
                                     'date_canceled'])

# 或者
# 将已有列转换为 datetime 列
marketing['date_served'] = pd.to_datetime(
    marketing['date_served']
)
使用 pandas 分析营销活动

日期列

# 或者逐列转换
# 将已有列转换为 datetime 列
marketing['date_served'] = pd.to_datetime(
    marketing['date_served']
)
使用 pandas 分析营销活动

日期列

marketing['day_served'] = marketing['date_served']\
                       .dt.dayofweek
使用 pandas 分析营销活动

Passons à la pratique !

使用 pandas 分析营销活动

Preparing Video For Download...