1. 程式人生 > >PythonML_ready

PythonML_ready

map,apply,applymap,groupby


import os
import pandas as pd
import numpy as np
import seaborn as sns
import requests
import matplotlib.pyplot as plt
plt.style.use('ggplot')
%matplotlib inline

PATH = r'C:/Users/Administrator/Desktop/iris/'
r = requests.get('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data')
#print(r.text)
with open(PATH + 'iris.data' , 'w') as f:
    f.write(r.text)
    
os.chdir(PATH)

df = pd.read_csv(PATH + 'iris.data' , names = ['sepal length' , 'sepal width' , 'petal length' , 'petal width' , 'class'])


#Map操作,替換類別的名字,列轉變
df['class'] = df['class'].map({'Iris-setosa' : 'SET' , 'Iris-virginica' : 'VIR' , 'Iris-versicolor' : 'VER'})
df

#Apply對列操作
df['wide petal'] = df['petal width'].apply(lambda v : 1 if v >= 1.3 else 0) #如果petal width列中資料大於等於1.3,則新加的列wide petal中為1
df

#Apply對整個資料框操作
df['petal area'] = df.apply(lambda r : r['petal width'] * r['petal length'] , axis = 1)  #axis = 1 表示對行操作,axis=0表示對列操作
df

#ApplyMap為資料框所有的資料單元執行一個函式
df.applymap(lambda v : np.log(v) if isinstance(v , float) else v) #如果資料型別是float,則取對數

#Groupby進行分組
df.groupby('class').mean()  #分類後每種屬性的均值
df

df.groupby('class').describe()  #整體資訊分類後的描述
df

df.groupby('petal width')['class'].unique().to_frame()  #通過和每一個唯一類相關聯的花瓣寬度,對類別進行分組


#根據類別來分組花瓣寬度時,使用np.max和np.min這兩個函式,以及返回最大花瓣減去最小花瓣寬度的lambda函式
df.groupby('class')['petal width']\
.agg({'delta' : lambda x: x.max() - x.min() , 'max': np.max , 'min': np.min})