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)

推薦閱讀