python數(shù)據(jù)處理隨記

1.刪除變量:

df.drop(['‘變量名1,變量名2......’],axis=1,inplace=True)

2.刪除所有缺失值:

df.dropna(how='any',inplace=True)? #‘a(chǎn)ny’有一個維度缺失就都刪除

3.刪除指定變量的缺失值:

df.dropna(subset=['變量名1','變量名2],inplace=True)

3.1根據(jù)閾值刪除缺失值:

thresh_count=len(data)*0.4# 設(shè)定閥值data=data.dropna(thresh=thresh_count,axis=1)#若某一列數(shù)據(jù)缺失的數(shù)量超過閥值就會被刪除

4.刪除指定變量的重復(fù)值:

df.drop_duplicates(subset=['變量名'],inplace=True)

5.缺失值填充:

df.fillna(''值) #統(tǒng)一填充

df.fillna(value={'類別變量:df['類別變量'].mode()[0],'連續(xù)變量':指定值,'連續(xù)變量2':df['連續(xù)變量2'].mean()/median,inplace=True)

df.fillna({'': , '': ,})

5.1數(shù)值型變量缺失值處理

from sklearn.preprocessing import Imputer imr=Imputer(missing_values='NaN',strategy='mean',axis=0)# 針對axis=0 列來處理imr=imr.fit(loans[numColumns]) loans[numColumns]=imr.transform(loans[numColumns])

6.value.counts():查看某列中有多少不同值并計算每個不同值有多少重復(fù)值

7.按條件對變量中指定值重新賦值:

df['變量'][df['變量'] == '舊值']? = '新值'

df['變量名']=df['變量名'].replace(['就值1','就值2'],[新值1,新值2])

df.replace({:,:})

train.loc[train['delinq_2yrs']>0,'delinq_2yrs'] = '1+'

8.按條件篩選數(shù)據(jù):

df=df[df['變量名']</>/!=/=數(shù)值]

df[~(df.a ==1)]

df.query(‘變量名>90’)

9.類別型變量描述統(tǒng)計:

df.describe(include='object')

#df.describe(include='all')

10.數(shù)值處理:

df['變量']=round(df['變量'],2) # 保留兩位小數(shù)

df['變量']=round(df['變量']) # 保留整數(shù)位

11.格式轉(zhuǎn)換:

df['變量']=df['變量'].astype('object')

df['變量']=df['變量'].astype('float64')

df.Fare=[int(x) for x in df.Fare]

12.查看因變量比例餅圖:df.groupby('Y').size()

plt.axes(aspect='equal')

counts=df['Y'].value_counts()

plt.pie(x=counts,labels=pd.Series(counts.index),autopct='%.2f%%')

plt.show()

13.類別型變量柱狀圖繪制:

plt.rcParams['font.sans-serif']=['SimHei']? #用來正常顯示中文標(biāo)簽

plt.rcParams['axes.unicode_minus']=False? #用來正常顯示負(fù)號

plt.bar(np.arange(len(df['類別變量'].value_counts())),df['類別變量'].value_counts())

#plt.title()

#plt.xlabel()

#plt.ylabel()

plt.xticks(np.arange(len(df['類別變量'].value_counts())),df['類別變量'].value_counts().index)

for x,y in zip(np.arange(len(df['類別變量'].value_counts())),df['類別變量'].value_counts()):

? ? plt.text(x,y,y,ha='center',va='bottom')

14.變量關(guān)系圖:

sns.heatmap(df.corr(),vmin=-1,vmax=1,cmap='Blue,annot=True)

15.箱線圖:

df.boxplot()

16.數(shù)據(jù)保存本地:

df.to_csv('命名.csv',encoding="utf_8_sig")

17.設(shè)置列表:

vlist=pd.DataFrame([x1,x2,x3],index=['x1','x2','x3' ,columns=['IV'])

18.重置索引:

df=df.reset_index(drop=True,inplace=False)

19.讀取了文件后,Pandas會把文件的一行作為列的索引標(biāo)簽,使用行數(shù)字作為行的索引標(biāo)簽:


數(shù)據(jù).index.name = 'date'

數(shù)據(jù).columns.name = 'code'

20.轉(zhuǎn)換列名:

df.rename(columns=states,inplace=True)? #states 為需要改變的列名的字典

21.隨機生成數(shù)據(jù):

np.random.randn()

22.尋找每行最大值、索引,并添加到數(shù)據(jù):

arr['max_value']=arr.max(axis=1)

arr['max_index']=np.argmax(array,axis=1)

23.數(shù)字格式化:

Python format 格式化函數(shù) | 菜鳥教程

24.啞變量處理:

pd.get_dummies()

n_columns=["a" , "b"]? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? dummy_df=pd.get_dummies(loans[n_columns])# 用get_dummies進行one hot編碼loans=pd.concat([loans , dummy_df],axis=1)

25.去除字符串:

df['變量'].str.strip("需要去除的字符串").astype(float) #通常用于處理字符串轉(zhuǎn)數(shù)字

26.時間處理格式:

df.變量=pd.to_datetime(df.變量,format='%Y/%m/%d') # 原日期格式為:2018/09/10

df['max']=pd.datetime.today().year-df.earliest_cr_line.dt.year # 計算日期到今天的時間

27.相關(guān)系數(shù):

stats.pearsonr(df.x1, df.y)

28.數(shù)據(jù)透視表:

pandas.pivot_table 函數(shù)中包含四個主要的變量,以及一些可選擇使用的參數(shù)。四個主要的變量分別是數(shù)據(jù)源 data,行索引 index,列 columns,和數(shù)值 values??蛇x擇使用的參數(shù)包括數(shù)值的匯總方式,NaN值的處理方式,以及是否顯示匯總行數(shù)據(jù)等。

df.pivot_table(values='因變量',index='需分組的變量',aggfunc=np.mean)

df[['因變量','需分組變量']].groupby(['需分組變量'],as_index=False).mean()? #分組聚合

29.根據(jù)類型篩選變量:

df.select_dtypes(include=["object"]).columns

30.數(shù)據(jù)標(biāo)準(zhǔn)化:

scaler = StandardScaler()

X = scaler.fit_transform(X)

sc = StandardScaler()? # 初始化縮放器loans_ml_df[col]=sc.fit_transform(loans_ml_df[col])? #對數(shù)據(jù)進行標(biāo)準(zhǔn)化

31.排序:

serier: sort_index(axis=1,ascending=False)、.order()

dataframe:sort_index(by='')

sort_values(ascending=False)

32.拼接:

pd.merge(left,right,on['',''],how='outer)/pd.merge(df1,df2,how='inner')

33.替換缺失值:

df.replace(-1,np.nan)

34.找出具體缺失值:

df[df.isnull().values==True]

35.有序特征的映射:

mapping_dict={"emp_length":{"10+ years":10,"9 years":9,"8 years":8,"7 years":7,"6? ? years":6,"5years":5,"4years":4,"3 years":3,"2 years":2,"1 year":1,"< 1 year":0,"n/a":0}

loans=loans.replace(mapping_dict)#變量映射

36.標(biāo)準(zhǔn)化:

col=loans.select_dtypes(include=['int64','float64']).columns

len(col)out:78#78個特征

col=col.drop('loan_status')#剔除目標(biāo)變量

loans_ml_df=loans# 復(fù)制數(shù)據(jù)至變量

fromsklearn.preprocessingimportStandardScaler# 導(dǎo)入模塊

sc=StandardScaler()# 初始化縮放器

loans_ml_df[col]=sc.fit_transform(loans_ml_df[col])#對數(shù)據(jù)進行標(biāo)準(zhǔn)化

37groupby聚合:

groupby().agg([])

38.圖像位置:

import matplotlib.gridspec as gridspec


39.enumerate() 函數(shù)

enumerate() 函數(shù)用于將一個可遍歷的數(shù)據(jù)對象(如列表、元組或字符串)組合為一個索引序列,同時列出數(shù)據(jù)和數(shù)據(jù)下標(biāo),一般用在 for 循環(huán)當(dāng)中


40.特征轉(zhuǎn)換:

from sklearn.feature_extraction import DivtVectorizer


41.迭代:

zip()并行

chain()串行

42.最大值、最小值具體信息

df[df[''] == min/max()]

43.分類變量的每個值數(shù)量 至少不少于總數(shù)據(jù)的5%

44.按照區(qū)分層,每個區(qū)抽取400個樣本

get_sample(df,sampling='stratified',k=400,stratified=[''])

45.更換數(shù)據(jù):

def judgeLevel(df)

? ? if df['inq_last_6mths'] ==0:

? ? ? ? return 'C'

? ? else:

? ? ? ? return 'B'

df['inq_last_6mths'] = df.apply(lambda r: judgeLevel(r), axis=1)

df ['] = df[''].map(lambda x : 1 if x >1 else x)

46.異常值

可以分析中位數(shù)和眾數(shù)的關(guān)系,如果兩者的值差別很大,則說明眾數(shù)偏離群體較遠,那么這個眾數(shù)有可能是錯誤值。

abs(x[].mode().iloc[0,]-x[].median())/(x[].quantile(0.75)-x[].quantile(0.25)))

47.創(chuàng)建列

df.assign(new1,new2)

48.缺失值呀變量處理

df.a.isnull().apply(int)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容