👨?💻?作業中最近常用到pandas做資料處理和分析,總結了以下常用內容,
🥳如想下載到本地可訪問以下地址
pandas常用速查-github
pandas常用速查-gitee
pandas常用操作大全
- pandas常用速查
- 引入依賴
- 演算法相關依賴
- 獲取資料
- 生成df
- 重命名列
- 增加列
- 缺失值處理
- 獨熱編碼
- 替換值
- 洗掉列
- 資料篩選
- 差值計算
- 資料修改
- 時間格式轉換
- 設定索引列
- 折線圖
- 散點圖
- 柱狀圖
- 熱力圖
- 66個最常用的pandas資料分析函式
- 從各種不同的來源和格式匯入資料
- 匯出資料
- 創建測驗物件
- 查看、檢查資料
- 資料選取
- 資料清理
- 篩選,排序和分組依據
- 資料合并
- 資料統計
- 16個函式,用于資料清洗
- 1.cat函式
- 2.contains
- 3.startswith/endswith
- 4.count
- 5.get
- 6.len
- 7.upper/lower
- 8.pad+side引數/center
- 9.repeat
- 10.slice_replace
- 11.replace
- 12.replace
- 13.split方法+expand引數
- 14.strip/rstrip/lstrip
- 15.findall
- 16.extract/extractall
pandas常用速查
引入依賴
# 匯入模塊
import pymysql
import pandas as pd
import numpy as np
import time
# 資料庫
from sqlalchemy import create_engine
# 可視化
import matplotlib.pyplot as plt
# 如果你的設備是配備Retina螢屏的mac,可以在jupyter notebook中,使用下面一行代碼有效提高影像畫質
%config InlineBackend.figure_format = 'retina'
# 解決 plt 中文顯示的問題 mymac
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
# 設定顯示中文 需要先安裝字體 aistudio
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默認字體
plt.rcParams['axes.unicode_minus'] = False # 用來正常顯示負號
import seaborn as sns
# notebook渲染圖片
%matplotlib inline
import pyecharts
# 忽略版本問題
import warnings
warnings.filterwarnings("ignore")
# 下載中文字體
!wget https://mydueros.cdn.bcebos.com/font/simhei.ttf
# 將字體檔案復制到 matplotlib'字體路徑
!cp simhei.ttf /opt/conda/envs/python35-paddle120-env/Lib/python3,7/site-packages/matplotib/mpl-data/fonts.
# 一般只需要將字體檔案復制到系統字體田錄下即可,但是在 studio上該路徑沒有寫權限,所以此方法不能用
# !cp simhei. ttf /usr/share/fonts/
# 創建系統字體檔案路徑
!mkdir .fonts
# 復制檔案到該路徑
!cp simhei.ttf .fonts/
!rm -rf .cache/matplotlib

演算法相關依賴
# 資料歸一化
from sklearn.preprocessing import MinMaxScaler
# kmeans聚類
from sklearn.cluster import KMeans
# DBSCAN聚類
from sklearn.cluster import DBSCAN
# 線性回歸演算法
from sklearn.linear_model import LinearRegression
# 邏輯回歸演算法
from sklearn.linear_model import LogisticRegression
# 高斯貝葉斯
from sklearn.naive_bayes import GaussianNB
# 劃分訓練/測驗集
from sklearn.model_selection import train_test_split
# 準確度報告
from sklearn import metrics
# 矩陣報告和均方誤差
from sklearn.metrics import classification_report, mean_squared_error
獲取資料
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://root:root@127.0.0.1:3306/ry?charset=utf8')
# 查詢插入后相關表名及行數
result_query_sql = "use information_schema;"
engine.execute(result_query_sql)
result_query_sql = "SELECT table_name,table_rows FROM tables WHERE TABLE_NAME LIKE 'log%%' order by table_rows desc;"
df_result = pd.read_sql(result_query_sql, engine)

生成df
# list轉df
df_result = pd.DataFrame(pred,columns=['pred'])
df_result['actual'] = test_target
df_result
# df取子df
df_new = df_old[['col1','col2']]
# dict生成df
df_test = pd.DataFrame({'A':[0.587221, 0.135673, 0.135673, 0.135673, 0.135673],
'B':['a', 'b', 'c', 'd', 'e'],
'C':[1, 2, 3, 4, 5]})
# 指定列名
data = pd.DataFrame(dataset.data, columns=dataset.feature_names)
# 使用numpy生成20個指定分布(如標準正態分布)的數
tem = np.random.normal(0, 1, 20)
df3 = pd.DataFrame(tem)
# 生成一個和df長度相同的亂數dataframe
df1 = pd.DataFrame(pd.Series(np.random.randint(1, 10, 135)))
重命名列
# 重命名列
data_scaled = data_scaled.rename(columns={'本體油位': 'OILLV'})
增加列
# df2df
df_jj2yyb['r_time'] = pd.to_datetime(df_jj2yyb['cTime'])
# 新增一列根據salary將資料分為3組
bins = [0,5000, 20000, 50000]
group_names = ['低', '中', '高']
df['categories'] = pd.cut(df['salary'], bins, labels=group_names)
缺失值處理
# 檢查資料中是否含有任何缺失值
df.isnull().values.any()
# 查看每列資料缺失值情況
df.isnull().sum()
# 提取某列含有空值的行
df[df['日期'].isnull()]
# 輸出每列缺失值具體行數
for i in df.columns:
if df[i].count() != len(df):
row = df[i][df[i].isnull().values].index.tolist()
print('列名:"{}", 第{}行位置有缺失值'.format(i,row))
# 眾數填充
heart_df['Thal'].fillna(heart_df['Thal'].mode(dropna=True)[0], inplace=True)
# 連續值列的空值用平均值填充
dfcolumns = heart_df_encoded.columns.values.tolist()
for item in dfcolumns:
if heart_df_encoded[item].dtype == 'float':
heart_df_encoded[item].fillna(heart_df_encoded[item].median(), inplace=True)
獨熱編碼
df_encoded = pd.get_dummies(df_data)
替換值
# 按列值替換
num_encode = {
'AHD': {'No':0, "Yes":1},
}
heart_df.replace(num_encode,inplace=True)
洗掉列
df_jj2.drop(['coll_time', 'polar', 'conn_type', 'phase', 'id', 'Unnamed: 0'],axis=1,inplace=True)
資料篩選
# 取第33行資料
df.iloc[32]
# 某列以xxx字串開頭
df_jj2 = df_512.loc[df_512["transformer"].str.startswith('JJ2')]
df_jj2yya = df_jj2.loc[df_jj2["變壓器編號"]=='JJ2YYA']
# 提取第一列中不在第二列出現的數字
df['col1'][~df['col1'].isin(df['col2'])]
# 查找兩列值相等的行號
np.where(df.secondType == df.thirdType)
# 包含字串
results = df['grammer'].str.contains("Python")
# 提取列名
df.columns
# 查看某列唯一值(種類)
df['education'].nunique()
# 洗掉重復資料
df.drop_duplicates(inplace=True)
# 某列等于某值
df[df.col_name==0.587221]
# df.col_name==0.587221 各行判斷結果回傳值(True/False)
# 查看某列唯一值及計數
df_jj2["變壓器編號"].value_counts()
# 時間段篩選
df_jj2yyb_0501_0701 = df_jj2yyb[(df_jj2yyb['r_time'] >=pd.to_datetime('20200501')) & (df_jj2yyb['r_time'] <= pd.to_datetime('20200701'))]
# 數值篩選
df[(df['popularity'] > 3) & (df['popularity'] < 7)]
# 某列字串截取
df['Time'].str[0:8]
# 隨機取num行
ins_1 = df.sample(n=num)
# 資料去重
df.drop_duplicates(['grammer'])
# 按某列排序(降序)
df.sort_values("popularity",inplace=True, ascending=False)
# 取某列最大值所在行
df[df['popularity'] == df['popularity'].max()]
# 取某列最大num行
df.nlargest(num,'col_name')
# 最大num列畫橫向柱形圖
df.nlargest(10).plot(kind='barh')

差值計算
# axis=0或index表示上下移動, periods表示移動的次數,為正時向下移,為負時向上移動,
print(df.diff( periods=1, axis=‘index‘))
print(df.diff( periods=-1, axis=0))
# axis=1或columns表示左右移動,periods表示移動的次數,為正時向右移,為負時向左移動,
print(df.diff( periods=1, axis=‘columns‘))
print(df.diff( periods=-1, axis=1))
# 變化率計算
data['收盤價(元)'].pct_change()
# 以5個資料作為一個資料滑動視窗,在這個5個資料上取均值
df['收盤價(元)'].rolling(5).mean()
資料修改
# 洗掉最后一行
df = df.drop(labels=df.shape[0]-1)
# 添加一行資料['Perl',6.6]
row = {'grammer':'Perl','popularity':6.6}
df = df.append(row,ignore_index=True)
# 某列小數轉百分數
df.style.format({'data': '{0:.2%}'.format})
# 反轉行
df.iloc[::-1, :]
# 以兩列制作資料透視
pd.pivot_table(df,values=["salary","score"],index="positionId")
# 同時對兩列進行計算
df[["salary","score"]].agg([np.sum,np.mean,np.min])
# 對不同列執行不同的計算
df.agg({"salary":np.sum,"score":np.mean})
時間格式轉換
# 時間戳轉時間字串
df_jj2['cTime'] =df_jj2['coll_time'].apply(lambda x: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x)))
# 時間字串轉時間格式
df_jj2yyb['r_time'] = pd.to_datetime(df_jj2yyb['cTime'])
# 時間格式轉時間戳
dtime = pd.to_datetime(df_jj2yyb['r_time'])
v = (dtime.values - np.datetime64('1970-01-01T08:00:00Z')) / np.timedelta64(1, 'ms')
df_jj2yyb['timestamp'] = v
設定索引列
df_jj2yyb_small_noise = df_jj2yyb_small_noise.set_index('timestamp')
折線圖
fig, ax = plt.subplots()
df.plot(legend=True, ax=ax)
plt.legend(loc=1)
plt.show()

plt.figure(figsize=(20, 6))
plt.plot(max_iter_list, accuracy, color='red', marker='o',
markersize=10)
plt.title('Accuracy Vs max_iter Value')
plt.xlabel('max_iter Value')
plt.ylabel('Accuracy')

散點圖
plt.scatter(df[:, 0], df[:, 1], c="red", marker='o', label='lable0')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=2)
plt.show()

柱狀圖
df = pd.Series(tree.feature_importances_, index=data.columns)
# 取某列最大Num行畫橫向柱形圖
df.nlargest(10).plot(kind='barh')


熱力圖
df_corr = combine.corr()
plt.figure(figsize=(20,20))
g=sns.heatmap(df_corr,annot=True,cmap="RdYlGn")

66個最常用的pandas資料分析函式
df #任何pandas DataFrame物件
s #任何pandas series物件
從各種不同的來源和格式匯入資料
pd.read_csv(filename) # 從CSV檔案
pd.read_table(filename) # 從分隔的文本檔案(例如CSV)中
pd.read_excel(filename) # 從Excel檔案
pd.read_sql(query, connection_object) # 從SQL表/資料庫中讀取
pd.read_json(json_string) # 從JSON格式的字串,URL或檔案中讀取,
pd.read_html(url) # 決議html URL,字串或檔案,并將表提取到資料幀串列
pd.read_clipboard() # 獲取剪貼板的內容并將其傳遞給 read_table()
pd.DataFrame(dict) # 從字典中,列名稱的鍵,串列中的資料的值
匯出資料
df.to_csv(filename) # 寫入CSV檔案
df.to_excel(filename) # 寫入Excel檔案
df.to_sql(table_name, connection_object) # 寫入SQL表
df.to_json(filename) # 以JSON格式寫入檔案
創建測驗物件
pd.DataFrame(np.random.rand(20,5)) # 5列20行隨機浮點數 pd.Series(my_list) # 從一個可迭代的序列創建一個序列 my_list
df.index = pd.date_range('1900/1/30', periods=df.shape[0]) # 添加日期索引
查看、檢查資料
df.head(n) # DataFrame的前n行
df.tail(n) # DataFrame的最后n行
df.shape # 行數和列數
df.info() # 索引,資料型別和記憶體資訊
df.describe() # 數值列的摘要統計資訊
s.value_counts(dropna=False) # 查看唯一值和計數
df.apply(pd.Series.value_counts) # 所有列的唯一值和計數
資料選取
使用這些命令選擇資料的特定子集,
df[col] # 回傳帶有標簽col的列
df[[col1, col2]] # 回傳列作為新的DataFrame
s.iloc[0] # 按位置選擇
s.loc['index_one'] # 按索引選擇
df.iloc[0,:] # 第一行
df.iloc[0,0] # 第一欄的第一元素
資料清理
df.columns = ['a','b','c'] # 重命名列
pd.isnull() # 空值檢查,回傳Boolean Arrray
pd.notnull() # 與pd.isnull() 相反
df.dropna() # 洗掉所有包含空值的行
df.dropna(axis=1) # 洗掉所有包含空值的列
df.dropna(axis=1,thresh=n) # 洗掉所有具有少于n個非null值的行
df.fillna(x) # 將所有空值替換為x
s.fillna(s.mean()) # 用均值替換所有空值(均值可以用統計模塊中的幾乎所有函式替換 )
s.astype(float) # 將系列的資料型別轉換為float
s.replace(1,'one') # 1 用 'one'
s.replace([1,3],['one','three']) # 替換所有等于的值 替換為所有1 'one' ,并 3 用 'three' df.rename(columns=lambda x: x + 1) # 列的重命名
df.rename(columns={'old_name': 'new_ name'})# 選擇性重命名
df.set_index('column_one') # 更改索引
df.rename(index=lambda x: x + 1) # 大規模重命名索引
篩選,排序和分組依據
df[df[col] > 0.5] # 列 col 大于 0.5 df[(df[col] > 0.5) & (df[col] < 0.7)] # 小于 0.7 大于0.5的行
df.sort_values(col1) # 按col1升序對值進行排序
df.sort_values(col2,ascending=False) # 按col2 降序對值進行 排序
df.sort_values([col1,col2],ascending=[True,False]) #按 col1 升序排序,然后 col2 按降序排序
df.groupby(col) #從一個欄回傳GROUPBY物件
df.groupby([col1,col2]) # 回傳來自多個列的groupby物件
df.groupby(col1)[col2] # 回傳中的值的平均值 col2,按中的值分組 col1 (平均值可以用統計模塊中的幾乎所有函式替換 )
df.pivot_table(index=col1,values=[col2,col3],aggfunc=mean) # 創建一個資料透視表組通過 col1 ,并計算平均值的 col2 和 col3
df.groupby(col1).agg(np.mean) # 在所有列中找到每個唯一col1 組的平均值
df.apply(np.mean) #np.mean() 在每列上應用該函式
df.apply(np.max,axis=1) # np.max() 在每行上應用功能
資料合并
df1.append(df2) # 將df2添加 df1的末尾 (各列應相同)
pd.concat([df1, df2],axis=1) # 將 df1的列添加到df2的末尾 (行應相同)
df1.join(df2,on=col1,how='inner') # SQL樣式將列 df1 與 df2 行所在的列col 具有相同值的列連接起來,'how'可以是一個 'left', 'right', 'outer', 'inner'
資料統計
df.describe() # 數值列的摘要統計資訊
df.mean() # 回傳均值的所有列
df.corr() # 回傳DataFrame中各列之間的相關性
df.count() # 回傳非空值的每個資料幀列中的數字
df.max() # 回傳每列中的最高值
df.min() # 回傳每一列中的最小值
df.median() # 回傳每列的中位數
df.std() # 回傳每列的標準偏差
16個函式,用于資料清洗
# 匯入資料集
import pandas as pd
df ={'姓名':[' 黃同學','黃至尊','黃老邪 ','陳大美','孫尚香'],
'英文名':['Huang tong_xue','huang zhi_zun','Huang Lao_xie','Chen Da_mei','sun shang_xiang'],
'性別':['男','women','men','女','男'],
'身份證':['463895200003128433','429475199912122345','420934199110102311','431085200005230122','420953199509082345'],
'身高':['mid:175_good','low:165_bad','low:159_bad','high:180_verygood','low:172_bad'],
'家庭住址':['湖北廣水','河南信陽','廣西桂林','湖北孝感','廣東廣州'],
'電話號碼':['13434813546','19748672895','16728613064','14561586431','19384683910'],
'收入':['1.1萬','8.5千','0.9萬','6.5千','2.0萬']}
df = pd.DataFrame(df)
df
1.cat函式
用于字串的拼接
df["姓名"].str.cat(df["家庭住址"],sep='-'*3)
2.contains
判斷某個字串是否包含給定字符
df["家庭住址"].str.contains("廣")
3.startswith/endswith
判斷某個字串是否以…開頭/結尾
# 第一個行的“ 黃偉”是以空格開頭的
df["姓名"].str.startswith("黃")
df["英文名"].str.endswith("e")
4.count
計算給定字符在字串中出現的次數
df["電話號碼"].str.count("3")
5.get
獲取指定位置的字串
df["姓名"].str.get(-1)
df["身高"].str.split(":")
df["身高"].str.split(":").str.get(0)
6.len
計算字串長度
df["性別"].str.len()
7.upper/lower
英文大小寫轉換
df["英文名"].str.upper()
df["英文名"].str.lower()
8.pad+side引數/center
在字串的左邊、右邊或左右兩邊添加給定字符
df["家庭住址"].str.pad(10,fillchar="*") # 相當于ljust()
df["家庭住址"].str.pad(10,side="right",fillchar="*") # 相當于rjust()
df["家庭住址"].str.center(10,fillchar="*")
9.repeat
重復字串幾次
df["性別"].str.repeat(3)
10.slice_replace
使用給定的字串,替換指定的位置的字符
df["電話號碼"].str.slice_replace(4,8,"*"*4)
11.replace
將指定位置的字符,替換為給定的字串
df["身高"].str.replace(":","-")
12.replace
將指定位置的字符,替換為給定的字串(接受正則運算式)
- replace中傳入正則運算式,才叫好用;
- 先不要管下面這個案例有沒有用,你只需要知道,使用正則做資料清洗多好用;
df["收入"].str.replace("\d+\.\d+","正則")
13.split方法+expand引數
搭配join方法功能很強大
# 普通用法
df["身高"].str.split(":")
# split方法,搭配expand引數
df[["身高描述","final身高"]] = df["身高"].str.split(":",expand=True)
df
# split方法搭配join方法
df["身高"].str.split(":").str.join("?"*5)
14.strip/rstrip/lstrip
去除空白符、換行符
df["姓名"].str.len()
df["姓名"] = df["姓名"].str.strip()
df["姓名"].str.len()
15.findall
利用正則運算式,去字串中匹配,回傳查找結果的串列
- findall使用正則運算式,做資料清洗,真的很香!
df["身高"]
df["身高"].str.findall("[a-zA-Z]+")
16.extract/extractall
接受正則運算式,抽取匹配的字串(一定要加上括號)
df["身高"].str.extract("([a-zA-Z]+)")
# extractall提取得到復合索引
df["身高"].str.extractall("([a-zA-Z]+)")
# extract搭配expand引數
df["身高"].str.extract("([a-zA-Z]+).*?([a-zA-Z]+)",expand=True)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/271354.html
標籤:python
