使用Pandas进行数据分析
介绍通过分析电信运营商的客户离网率数据集来熟悉Pandas数据分析,并构建一个预测客户离网率的简单模型#导入必要的包import numpy as npimport pandas as pdimport warningswarnings.filterwarnings('ignore')#读取数据df = pd.read_csv('https://labfile.oss.aliyuncs.com/c
·
介绍
通过分析电信运营商的客户离网率数据集来熟悉Pandas数据分析,并构建一个预测客户离网率的简单模型
#导入必要的包
import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
#读取数据
df = pd.read_csv(
'https://labfile.oss.aliyuncs.com/courses/1283/telecom_churn.csv')
df.head()
#查看数据库的维度、特征名称和特征类型
df.shape
#打印所有列名
df.columns
#输出DataFrame的一些总体信息
df.info()
#astype()方法可以更改列的类型
df['Churn'] = df['Churn'].astype('int64')
#describe()方法可以显示数值特征(int64和float64)的基本统计学特性,如未缺失值的数值、均值、标准差、范围、四分位数等。
df.describe()
#通过include参数显式指定包含的数据类型
df.describe(include=['object', 'bool'])
#value_counts()方法可以查看类别和布尔值特征
df['Churn'].value_counts()
#调用 value_counts() 函数时,加上 normalize=True 参数可以显示比例
df['Churn'].value_counts(normalize=True)
#根据每日消费额排序(设置 ascending=False 倒序排列)
df.sort_values(by='Total day charge', ascending=False).head()
#先按 Churn 离网率 升序排列,再按 Total day charge 每日总话费 降序排列,优先级 Churn > Tatal day charge
df.sort_values(by=['Churn', 'Total day charge'],
ascending=[True, False]).head()
df['Churn'].mean()
df[df['Churn'] == 1].mean()
df[df['Churn'] == 1]['Total day minutes'].mean()
df[(df['Churn'] == 0) & (df['International plan'] == 'No')
]['Total intl minutes'].max()
# 通过 loc 方法输出 0 至 5 行、State 州 至 Area code 区号 的数据
df.loc[0:5, 'State':'Area code']
# 通过 iloc 方法输出前 5 行的前 3 列数据
df.iloc[0:5, 0:3]
#df[:1] 和 df[-1:] 可以得到 DataFrame 的首行和末行
df[-1:]
# 通过 apply() 方法应用函数 max 至每一列,即输出每列的最大值
df.apply(np.max)
df[df['State'].apply(lambda state: state[0] == 'W')].head()
# map() 方法可以通过一个 {old_value:new_value} 形式的字典替换某一列中的值
d = {'No': False, 'Yes': True}
df['International plan'] = df['International plan'].map(d)
df.head()
df = df.replace({'Voice mail plan': d})
df.head()
# 根据Churn离网率变量的值对数据进行分组,显示每组的统计数据
columns_to_show = ['Total day minutes', 'Total eve minutes',
'Total night minutes']
df.groupby(['Churn'])[columns_to_show].describe(percentiles=[])
# 通过agg()方法对分组后的数据进行聚合
columns_to_show = ['Total day minutes', 'Total eve minutes',
'Total night minutes']
df.groupby(['Churn'])[columns_to_show].agg([np.mean, np.std, np.min, np.max])
# 通过pivot_table()方法查看不同区号下白天、夜晚、深夜的电话量的均值
df.pivot_table(['Total day calls', 'Total eve calls', 'Total night calls'],
['Area code'], aggfunc='mean')
#构建交叉表查看样本的Churn离网率和International plan国际套餐的分布情况
pd.crosstab(df['Churn'], df['International plan'])
#构建交叉表查看Churn离网率和Voice mail plan语音邮件套餐的分布情况
pd.crosstab(df['Churn'], df['Voice mail plan'], normalize=True)
total_calls = df['Total day calls'] + df['Total eve calls'] + \
df['Total night calls'] + df['Total intl calls']
# loc 参数是插入 Series 对象后选择的列数
# 设置为 len(df.columns)以便将计算后的 Total calls 粘贴到最后一列
df.insert(loc=len(df.columns), column='Total calls', value=total_calls)
df.head()
df['Total charge'] = df['Total day charge'] + df['Total eve charge'] + \
df['Total night charge'] + df['Total intl charge']
df.head()
# 移除先前创捷的列
df.drop(['Total charge', 'Total calls'], axis=1, inplace=True)
# 删除行
df.drop([1, 2]).head()
预测离网率
# 加载模块,配置绘图
import matplotlib.pyplot as plt
import seaborn as sns
# 使用countplot()方法构建计数直方图来可视化结果
sns.countplot(x='International plan', hue='Churn', data=df)
# 通过crosstab()构建一个交叉表来查看Customer service calls客服呼叫变量与Churn离网率的相关性,并可视化结果
pd.crosstab(df['Churn'], df['Customer service calls'], margins=True)
sns.countplot(x='Customer service calls', hue='Churn', data=df)
#给DataFrame添加一个二元属性Many_service_calls,即客户呼叫超过2次,查看Customer service客服呼叫和Churn离网率的相关性,并可视化结果
df['Many_service_calls'] = (df['Customer service calls'] > 3).astype('int')
pd.crosstab(df['Many_service_calls'], df['Churn'], margins=True)
sns.countplot(x='Many_service_calls', hue='Churn', data=df)
#将Churn离网率与International plan国际套餐及新创建的Many_service_calls多次客服呼叫关联起来
pd.crosstab(df['Many_service_calls'] & df['International plan'], df['Churn'])
- 对数据进行归一化处理的目的是:使得预处理的数据被限定在一定的范围内,从而消除奇异样本数据导致的不良影响。
更多推荐
已为社区贡献1条内容
所有评论(0)