Python資料預處理(刪除重複值和空值)

2021-09-25 10:35:57 字數 1607 閱讀 7408

pandas幾個函式的使用,大資料的預處理(刪除重複值和空值),人工刪除很麻煩

python恰好能夠解決

注釋很詳細在這不一一解釋了

######################################

##### 讀寫excel(xls\xlsx)檔案

import pandas as pd

import numpy as np

df_excel = pd.read_excel('data3.xlsx')

print('資料量行*列',df_excel.shape)

# # df_excel.to_excel('df_excel.xlsx',header=none)#生成檔案儲存,無表頭

print('資料集中存在重複觀測的數量:\n',np.sum(df_excel.duplicated())) #f為不存在,t為存在,用sum顯示重複的數量

print('刪除行重複後的資料\n',df_excel.drop_duplicates(subset=none,keep='first',inplace=none))#excel檔案中設定第一和第二行為重複行,結果刪除了第二行保留第一行

###df_excel.drop_duplicates(subset=['a','b'],keep='first',inplace=true)

#### **中subset對應的值是列名,表示只考慮這兩列,將這兩列對應值相同的行進行去重。預設值為subset=none表示考慮所有列。

#####keep='first'表示保留第一次出現的重複行,是預設值。keep另外兩個取值為"last"和false,分別表示保留最後一次出現的重複行和去除所有重複行。

#####inplace=true表示直接在原來的dataframe上刪除重複項,而預設值false表示生成乙個副本

print('資料集列中是否存在缺失值:\n',df_excel.isnull().any()) #f為不存在,t為存在

print('每一行的缺失值個數:',df_excel.isnull().sum(axis=1))

print('每一列的缺失值個數:',df_excel.isnull().sum(axis=0))

####### df.isnull().sum(axis=0)每一列的缺失值個數

#####df.isnull().any()則會判斷哪些」列」存在缺失值

df=df_excel.dropna()

print(df_excel.dropna(thresh=5))

# #axis=0: 刪除包含缺失值(nan)的行

# #axis=1: 刪除包含缺失值(nan)的列

# # how=『any』 :要有缺失值(nan)出現刪除

# # how=『all』: 所有的值都缺失(nan)才刪除

# 還有乙個thresh引數

# thresh=n,保留至少有 n 個非 nan 數的行

######drop用法

print(df_excel.drop(['edu'],axis=1))#按照列刪除edu這一列

print(df_excel.drop([0],axis=0))#按照行刪除0這一行

Python資料預處理

1.匯入資料檔案 excel,csv,資料庫檔案等 df read table file,names 列名1,列名2,sep encoding file是檔案路徑,names預設為檔案的第一行為列名,sep為分隔符,預設為空,表示預設匯入為一列 encoding設定檔案編碼,匯入中文時,需設定utf...

python資料預處理

scikit learn 提供的binarizer能夠將資料二元化 from sklearn.preprocessing import binarizer x 1,2,3,4,5 5,4,3,2,1 3,3,3,3,3 1,1,1,1,1 print before transform x binar...

python資料預處理

import pandas as pd 缺失值處理 df pd.read excel users caizhengjie desktop a.xlsx print df 直接呼叫info方法就會返回每一列的缺失值 print df.info print isnull方法判斷哪個是缺失值 print ...