whystea2

xxxyyyxxxok發表於2024-07-28
assign df.assign( col3=df["col2"].str.upper(), col4=df["col1"] * 3 / 4 + 25, col5=lambda x: x["col1"] / 2 + 10, col6=lambda x: x["col5"] * 5, # 在col6計算中直接使用col5 col7=lambda x: x.col2.str.upper(), col8=lambda x: x.col7.str.title() # col8中使用col7 ) 與apply的區別是,會返回一個新的dataframe,原本的dataframe不會變 增 行 loc concat 列 [''] concat 刪 - drop 行 label axis=0 index 列 label axis=1 colunms dropna import pandas as pd axis=0或axis='index’刪除含有缺失值的行 axis=1或axis='columns’刪除含有缺失值的列 thresh表示保留至少有threash個的 # 建立包含缺失值的資料框 data = {'A': [1, 2, None, 4], 'B': [None, 6, 7, 8], 'C': [9, 10, 11, 12]} df = pd.DataFrame(data) # 刪除包含缺失值的行 cleaned_df = df.dropna() # 刪除包含缺失值的列 cleaned_df = df.dropna(axis=1) # 只刪除整行或整列都是缺失值的行或列 cleaned_df = df.dropna(how='all') # 至少需要2個非缺失值才保留行或列 cleaned_df = df.dropna(thresh=2) # 只在特定列中檢查缺失值 cleaned_df = df.dropna(subset=['A', 'C']) # 在原始資料上進行就地修改 df.dropna(inplace=True) roc曲線、auc值 fpr,tpr,_=roc_curve(y_test,y_score) auc=auc(fpr,tpr) plt.plot(fpr,tpr,label='ROC curve (area=%.2f)'%auc) plt.plot([0,1],[0,1],linestyle='--') subplot -不同圖之間的間隔 pyplot.subplots_adjust() param: left,right,bottom,top 0-1 之間是指在整張圖的百分比 wspace 子圖之間橫向間隔 hspace 子圖之間縱向間隔 -標題 pyplot.title param: label:顯示內容 loc:(center|left|right)顯示位置 y:1.0是在top pad:距離top的間隔 顏色 字型 標記 https://www.bilibili.com/video/BV18f4y1u7tK/?vd_source=ec7740b3018d25c8c0c9e384eb9c44b7 plt.text(x,y,text) plt.annotate(text,xy,xytext,arrowprops=dict(arrowstyle='-->')) 線型 -橫縱座標標記 pyplot.xticks() param: ticks:表示顯示標題的位置 labels:位置上顯示的內容 rotation:旋轉的角度 plt.xticks([1,2,3,4,5],['yi','er','san','si','wu']) -橫縱座標內容 pyplot.xlabel() param: xlabel labelpad loc -橫縱座標顯示範圍 pyplot.xlim() 1.返回現在的範圍 2.left=1,right=5 設定顯示的座標軸範圍 圖示 https://zhuanlan.zhihu.com/p/651600668 標上y值 圖型別 suplots、ax # using the variable ax for single a Axes fig, ax = plt.subplots() # using the variable axs for multiple Axes fig, axs = plt.subplots(2, 2) # using tuple unpacking for multiple Axes fig, (ax1, ax2) = plt.subplots(1, 2) fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) 中文顯示 plt.rcParams['font.sans-serif']=['SimHei'] plt.rcParams['axes.unicode_minus']=False apply、map https://zhuanlan.zhihu.com/p/584036056 map常用於字典對映 如果只對映部分,會將未對映的變為None apply常用於函式,可以額外新增引數,可用於列函式對映對應,axis可選0、1 0-列 1-行 #引數 df['Python優秀'] = df['Python成績'].apply(get_python_Goodornot, args=(80,)) #對映 df['Python成績'].apply({'A':lambda x:x+1, 'B':lambda x:x+2}) #每個人的最大成績 1-行 #apply 可以用於多維 df[['Python成績', '英語成績']].apply(np.max, axis=1) df[['Python成績', '英語成績']].apply(lambda x:x['Python成績']-x['英語成績'], axis=1) #每科的最大成績 0-列 df[['Python成績', '語文成績', '數學成績', '英語成績']].apply(np.max, axis=0) applymap用於整個的每一個 quantile df.quantile(0.2) interplot df.interpolate() param: method:linear、index、time fillna df.fillna() param: value: method:ffill、bfill 向前、向後 limit:連續na時,最多填補的個數 >>> df = pd.DataFrame([[np.nan, 2, np.nan, 0], [3, 4, np.nan, 1], [np.nan, np.nan, np.nan, 5], [np.nan, 3, np.nan, 4]], columns=list("ABCD")) >>> df A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 2 NaN NaN NaN 5 3 NaN 3.0 NaN 4 >>> df.fillna(method="ffill") A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 2 3.0 4.0 NaN 5 3 3.0 3.0 NaN 4 >>> values = {"A": 0, "B": 1, "C": 2, "D": 3} >>> df.fillna(value=values) A B C D 0 0.0 2.0 2.0 0 1 3.0 4.0 2.0 1 2 0.0 1.0 2.0 5 3 0.0 3.0 2.0 4 >>> df.fillna(value=values, limit=1) A B C D 0 0.0 2.0 2.0 0 1 3.0 4.0 NaN 1 2 NaN 1.0 NaN 5 3 NaN 3.0 NaN 4 //照著另一個df填充 >>> df2 = pd.DataFrame(np.zeros((4, 4)), columns=list("ABCE")) >>> df.fillna(df2) A B C D 0 0.0 2.0 0.0 0 1 3.0 4.0 0.0 1 2 0.0 0.0 0.0 5 3 0.0 3.0 0.0 4 rank - https://zhuanlan.zhihu.com/p/635129284 param: ascending:True,False method: average:相同排名下,取平均值進行排名。比如李四、王五為第二、第三名,孫7為第四名,那麼李四、王五取值為2.5,孫7取值為4。 min:相同排名下,取較小的排名。比如李四、王五為第二、第三名,孫7為第四名,那麼李四、王五取值為2,孫7取值為4。 max:相同排名下,取較大的排名。比如李四、王五為第二、第三名,孫7為第四名,那麼李四、王五取值為3,孫7取值為4。 first:相同排名下,按原來的順序進行排序。比如李四、王五為第二、第三名,孫7為第四名,那麼李四取值為2,王五取值為3,孫7取值為4。 dense:類似min,不過後續值排名在此排名基礎上加一。比如李四、王五為第二、第三名,孫7為第四名,那麼李四、王五取值為2,孫7取值為3。 pct:百分比顯示 df['班級Python成績排名'] = df.groupby('班級')['Python成績'].rank(method='min', ascending=False) sample param: frac:百分比 n:抽樣多少個數 replace: frac>1 or n>數 時 replace 只能為true groupby -https://zhuanlan.zhihu.com/p/607906239?utm_id=0&wd=&eqid=cfdd347c00082b9e00000004646b4463 param: by group_keys:true 使用by列作為索引 false 使用原索引 #多個聚合 df.groupby(by='區域')['利潤'].agg(['max','min','mean']) #多層 df.groupby(by='類別').agg({'利潤':['max','min','mean'],'銷售額':['max','min','mean']} #自定義新列名 df.groupby(by='類別').agg(總銷售額=('銷售額','sum'),總利潤=('利潤','sum'),平均利潤=('利潤',profit_mean)) #分組時使用apply df.groupby(by='類別').agg(總銷售額=('銷售額','sum'),總利潤=('利潤','sum'),平均利潤=('利潤',profit_mean)) #聚合時使用apply df.groupby(by='區域')['產品名稱'].apply(lambda x : x.str.contains('紅色').sum()) #sort_values排序 df.groupby(by=['區域',df.訂單日期.apply(lambda x : x.year)],group_keys=False).agg({'銷售額':'sum'}).sort_values(by=['銷售額'],ascending=False).reset_index().groupby('區域').first() #修改索引名 多個索引 df_group = df.groupby(by=['區域',df.訂單日期.apply(lambda x : x.year)],group_keys=False).agg({'銷售額':'sum'}) # df_group.index.names = ['區域','年份'] df_group = df_group.rename_axis(['區域','年份']) #transform df_group['avg_profit'] = df_group.groupby('區域')['平均利潤'].transform('mean') #filter f.groupby(by='子類別').filter(lambda x:x.數量.sum() > 1000) insert df.insert(loc,column,value) -插入新列 >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}) >>> df col1 col2 0 1 3 1 2 4 >>> df.insert(1, "newcol", [99, 99]) >>> df col1 newcol col2 0 1 99 3 1 2 99 4 >>> df.insert(0, "col1", [100, 100], allow_duplicates=True) >>> df col1 col1 newcol col2 0 100 1 99 3 1 100 2 99 4 pop df.pop(item) 刪除並返回列名為item的列 sort_index -https://zhuanlan.zhihu.com/p/584671020 sort_values -https://zhuanlan.zhihu.com/p/584671020 df.sort_values(by=['Python成績', '年齡'], axis=0, ascending=[False, True], inplace=True, na_position='last') pivot mulindex pivot_table cut、qcut 只設定分的箱子數時 qcut 基於分位數,所以基本每個箱子裡的個數相同 cut 基於區間大小,所以基本每個箱子裡的大小範圍相同 cut可以自定義邊界 cut param: q-箱子個數 bins-邊界 label-新的箱子名 qcut param: q-箱子個數 label-新的箱子名 qcut retbins=True , 可以返回邊界,Whether to return the (bins, labels) or not. _,bins=pd.qcut(a,3,labels=['yi','er','san'],retbins=True) category -https://blog.csdn.net/superfjj/article/details/118305330 rolling ffill diff!!!! df.diff(2) 向下移動兩行後減去原列 cum shift pipe reset_index transform 複合索引列名的修改 svc、svr SVC-分類 SVR-迴歸 predict_proba #二分類 計算roc cls.predict_proba(t_x_test)[:,1] #多分類 計算roc best_cls.predict_proba(m_x_test) 多分類評價指標 acc=accuracy_score(m_y_test,m_y_p) recall=recall_score(m_y_test,m_y_p,average='micro') precision=precision_score(m_y_test,m_y_p,average='micro') f1=f1_score(m_y_test,m_y_p,average='micro') auc=roc_auc_score(m_y_test,m_y_pro,multi_class='ovr') 輸出格式控制 print('名字是 %s,年齡是%s' % (name ,age)) %6.3f axis 數學計算時 axis=0 跨行 index,row series axis=1 跨列 column 修改列名,透過index 離散化 -get_dummies、onehot keras lstm-https://blog.csdn.net/qq_43703185/article/details/120494402 scoring引數輸入 Classification -f1 -f1_micro Clustering -rand_score Regression -neg_mean_absolute_error -r2 -neg_mean_squared_error heatmap形式 - https://www.cnblogs.com/ethan-wen/p/17405999.html,https://scikit-learn.org/stable/modules/model_evaluation.html#multimetric-scoring where mask seaborn heatmap pie 特徵選擇、特徵降維、長短、樣本不平衡,離散化 長短 pivot_table https://zhuanlan.zhihu.com/p/482192478 形成一個有列有行索引的表 列-index-groupby的by 行-value-groupby後挑選的列 計算-aggfunc-分組計算 melt https://zhuanlan.zhihu.com/p/482192478 MultiIndex https://blog.csdn.net/conving/article/details/120185108 index=[["a","a","b","b","c","c"], ["期末","期中","期末","期中","期末","期中"]] names=["a","b","c"] exems=["期中","期末"] index=pd.MultiIndex.from_product([names,exems]) df3.set_index(["class","name"]) -列名 data1.sort_index(level=0,ascending=False) shift,rolling https://zhuanlan.zhihu.com/p/587349753?utm_id=0 # 計算差值 df_shift['one_week_net'] = df_shift.sales - df_shift.sales.shift(-7) 異常值->補全->標準化->降維/特徵選擇->取樣 異常 -有nan normal_=(((data-data.mean())/data.std()).abs()>3).any(axis=1) -無nan isf=IsolationForest(contamination=0.1) isf.fit(dat2) pre=isf.predict(dat2) normal_=dat2.index[pre==-1] 補全 knn kim=KNNImputer(n_neighbors=3) dat1.loc[:,:]=kim.fit_transform(dat1) 降維 pca=PCA(n_components=2)//PCA(0.99) s=StandardScaler() pca_data.loc[:,:]=pca.fit_transform(s.fit_transform(data.iloc[:,:-1])) 特徵選擇 -有監督 feature_select=SelectKBest(mutual_info_regression,k=6) feature_select.fit_transform(x_df,y_y_df) x_df=x_df.loc[:,feature_select.get_support()] -無監督 feature_select=VarianceThreshold(0.2) feature_select.fit_transform(x_df) x_df=x_df.loc[:,feature_select.get_support()] onehot 啞變數 rain_data=pd.concat([train_data,pd.get_dummies(train_data['時間'].dt.quarter)],axis=1) 聚類繪圖