Python数据分析:实用向( 二 )

输出缺失值print ("Train age missing value: " + str((train.Age.isnull().sum()/len(train))*100)+str("%"))影响分析xgb输出特征重要性model_xgb= XGBClassifier()model_xgb.fit(X,y)from xgboost import plot_importanceplot_importance(model_xgb,height=0.5,color='green',title="')# plt.savefig("imp.png')plt.show()计算相关系数并画图【Python数据分析:实用向】plt.style.use('classic')plt.rcParams['font.sans-serif'] = ['SimHei']# 黑体plt.rcParams['axes.unicode_minus'] = False# 解决无法显示符号的问题plt.rc("figure", facecolor="white")#去除灰色边框plt.figure(figsize=(15,6),dpi=300)df_onehot.corr()['购买意愿'].sort_values(ascending=False).plot(kind='bar',color='dodgerblue')plt.savefig('buyvary1.png', dpi=300)plt.show()data.corr(method='pearson')data.corr(method='spearman')data.corr(method='kendall')Pandas处理常用操作

为dataframe添加1列
data['age']=list
合并表格再排序
data = https://www.huyubaike.com/biancheng/pd.concat([with_N, without_N], axis=0)data.sort_values(by ='目标客户编号', inplace=True)
dataframe排序
useful=useful.sort_values(by = ['购买难度'], ascending = [True])
选取指定行(以列的值筛?。?
first1=data3[(data3['品牌编号']==1)]获取列名
kf=list(data2.columns[1:7])for x in [9,11,12,20,21,24,25,26]:kf.append(data2.columns[x])print(kf)修改列名
#1、修改列名a,b为A、B 。df.columns = ['A','B']#2、只修改列名a为Adf.rename(columns={'a':'A'})删除一列
data3=data3.drop(1,axis=0)列表转dataframe(嵌套列表)
from pandas.core.frame import DataFramedata7=DataFrame(week)data7类型转换
Dataframe到Series
Series = Dataframe['column']
Series到list
list = Series.to_list()
list 转 array
array = np.array(list)
array 转 torch.Tensor
tensor = torch.from_numpy(array)
torch.Tensor 转 array
array = tensor.numpy()# gpu情况下需要如下的操作array = tensor.cpu().numpy()
torch.Tensor 转 list
# 先转numpy,后转listlist = tensor.numpy().tolist()
array 转 list
list = array.tolist()
list 转 torch.Tensor
tensor=torch.Tensor(list)
array或者list转Series
series = pd.Series({'a': array})series2 = pd.Series({'a': list})
list转dataframe
data4=DataFrame(li)
array转dataframe
df = pd.DataFrame(data=https://www.huyubaike.com/biancheng/data[0:,0:],columns='pregnants','Plasma_glucose_concentration','blood_pressure','Triceps_skin_fold_thickness','serum_insulin','BMI','Diabetes_pedigree_function','Age','Target'] )python需要注意的地方变量列表的复制:直接采用a=b的方式会指向同一个内存地址
全局变量:函数内部的变量,外部是无法访问的,在函数内部定义global 后函数运行过才可访问
循环
  • continue: 跳出本次循环
  • break: 跳出本层循环
运算矩阵numpy乘法:
  • 点乘: np.dot(xy)
  • 数乘: np.mat(x,int)
随机数import randomprint( random.randint(1,10) )# 产生 1 到 10 的一个整数型随机数print( random.random() )# 产生 0 到 1 之间的随机浮点数print( random.uniform(1.1,5.4) )# 产生1.1 到 5.4 之间的随机浮点数,区间可以不是整数print( random.choice('tomorrow') )# 从序列中随机选取一个元素print( random.randrange(1,100,2) )# 生成从1到100的间隔为2的随机整数a=[1,3,5,6,7]# 将序列a中的元素顺序打乱random.shuffle(a)print(a)import randomimport string# 随机整数:print random.randint(1,50)# 随机选取0到100间的偶数:print random.randrange(0, 101, 2)# 随机浮点数:print random.random()print random.uniform(1, 10)# 随机字符:print random.choice('abcdefghijklmnopqrstuvwxyz!@#$%^&*()')# 多个字符中生成指定数量的随机字符:print random.sample('zyxwvutsrqponmlkjihgfedcba',5)# 从a-zA-Z0-9生成指定数量的随机字符:ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))print ran_str# 多个字符中选取指定数量的字符组成新字符串:print ''.join(random.sample(['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'], 5))# 随机选取字符串:print random.choice(['剪刀', '石头', '布'])# 打乱排序items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]print random.shuffle(items)

推荐阅读