一、常用功能及函數簡介
包導入
一般我們需要做如下導入,numpy和pandas一般需要聯合使用:
import pandas as pd
import numpy as np
本文采用如下縮寫:
df:Pandas DataFrame對象
s: Pandas Series對象
數據導入
pd.read_csv(filename):從CSV文件導入數據
pd.read_table(filename):從限定分隔符的文本文件導入數據
pd.read_excel(filename):從Excel文件導入數據
pd.read_sql(query, connection_object):從SQL表/庫導入數據
pd.read_json(json_string):從JSON格式的字符串導入數據
pd.read_html(url):解析URL、字符串或者HTML文件
pd.read_clipboard():從粘貼板獲取內容
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)):創建20行5列的隨機數組成的DataFrame對象
pd.Series(my_list):從可迭代對象my_list創建一個Series對象
df.index = pd.date_range('1900/1/30', periods=df.shape[0]):增加一個日期索引
index和reindex聯合使用很有用處,index可作為索引並且元素亂排序之后,所以跟着元素保持不變,因此,當重拍元素時,只需要對index進行才重排即可:reindex。
另外, reindex時,還可以增加新的標為NaN的元素。
數據查看
df.head(n):查看DataFrame對象的前n行
df.tail(n):查看DataFrame對象的最后n行
df.shape():查看行數和列數
df.info():查看索引、數據類型和內存信息
df.describe():查看數值型列的匯總統計
s.value_counts(dropna=False):查看Series對象的唯一值和計數
df.apply(pd.Series.value_counts):查看DataFrame對象中每一列的唯一值和計數
apply的用處很多,比如可以通過跟lambda函數聯合,完成很多功能:將包含某個部分的元素挑出來等等。
cities['Is wide and has saint name'] = (cities['Area square miles'] > 50) & cities['City name'].apply(lambda name: name.startswith('San'))
數據選取
df[col]:根據列名,並以Series的形式返回列
df[[col1, col2]]:以DataFrame形式返回多列
s.iloc[0]:按位置選取數據
s.loc['index_one']:按索引選取數據
df.iloc[0,:]:返回第一行
數據清洗
df.columns = ['a','b','c']:重命名列名
pd.isnull():檢查DataFrame對象中的空值,並返回一個Boolean數組
pd.notnull():檢查DataFrame對象中的非空值,並返回一個Boolean數組
df.dropna():刪除所有包含空值的行
df.fillna(x):用x替換DataFrame對象中所有的空值
s.astype(float):將Series中的數據類型更改為float類型
s.replace(1,'one'):用‘one’代替所有等於1的值
df.rename(columns=lambda x: x + 1):批量更改列名
df.set_index('column_one'):更改索引列
數據處理:Filter, Sort, GroupBy
df[df[col] > 0.5]:選擇col列的值大於0.5的行
df.sort_values(col1):按照列col1排序數據,默認升序排列
df.groupby(col):返回一個按列col進行分組的Groupby對象
df.groupby(col1).agg(np.mean):返回按列col1分組的所有列的均值
df.pivot_table(index=col1, values=[col2,col3], aggfunc=max):創建一個按列col1進行分組,並計算col2和col3的最大值的數據透視表
data.apply(np.mean):對DataFrame中的每一列應用函數np.mean
數據合並
df1.append(df2):將df2中的行添加到df1的尾部
df.concat([df1, df2],axis=1):將df2中的列添加到df1的尾部
df1.join(df2,on=col1,how='inner'):對df1的列和df2的列執行SQL形式的join
數據統計
df.describe():查看數據值列的匯總統計
df.mean():返回所有列的均值
df.corr():返回列與列之間的相關系數
df.count():返回每一列中的非空值的個數
df.max():返回每一列的最大值
df.min():返回每一列的最小值
df.median():返回每一列的中位數
df.std():返回每一列的標准差
Pandas支持的數據類型
int 整型
float 浮點型
bool 布爾類型
object 字符串類型
category 種類
datetime 時間類型
補充:
df.astypes: 數據格式轉換
df.value_counts:相同數值的個數統計
df.hist(): 畫直方圖
df.get_dummies: one-hot編碼,將類型格式的屬性轉換成矩陣型的屬性。比如:三種顏色RGB,紅色編碼為[1 0 0]
參考文章:
Pandas官網
Pandas官方文檔
Pandas Cheat Sheet -- Python for Data Science
10 minutes to Pandas
二、房價預測案例
根據給定的訓練csv文件,預測給出的測試csv文件中的房價。
import numpy as np
import pandas as pd
from Cython.Shadow import inline
import matplotlib.pyplot as plt
#matplotlib inline
###################1 oridinal data##################
train_df = pd.read_csv('input/train.csv', index_col=0)#數據導入
test_df = pd.read_csv('input/test.csv', index_col=0)
print("type of train_df:" + str(type(train_df)))
#print(train_df.columns)
print("shape of train_df:" + str(train_df.shape))
print("shape of test_df:" + str(test_df.shape))
train_df.head()#數據查看
#print(train_df.head())
###################2 smooth label######################
prices = pd.DataFrame({"price":train_df["SalePrice"], "log(price+1)":np.log1p(train_df["SalePrice"])})
print("shape of prices:" + str(prices.shape))#數據創建
prices.hist()#直方圖
# plt.plot(alphas, test_scores)
# plt.title("Alpha vs CV Error")
plt.show()
y_train = np.log1p(train_df.pop('SalePrice'))
print("shape of y_train:" + str(y_train.shape))
###################3 take train and test data together##############
all_df = pd.concat((train_df, test_df), axis=0)#數據合並
print("shape of all_df:" + str(all_df.shape))
###################4 make category data to string####################
print(all_df['MSSubClass'].dtypes)
all_df['MSSubClass'] = all_df['MSSubClass'].astype(str)#數據格式轉換
all_df['MSSubClass'].value_counts()#相同數值個數統計
print(all_df['MSSubClass'].value_counts())
##################5 fill null###########################
all_dummy_df = pd.get_dummies(all_df)#one-hot編碼,顏色RGB,則R編碼為[1 0 0]
print(all_dummy_df.head())#下一行進行數據清洗,找到為空的屬性,並按照空的數量對屬性排序
print(all_dummy_df.isnull().sum().sort_values(ascending=False).head())
mean_cols = all_dummy_df.mean()#數據統計,均值
print(mean_cols.head(10))
all_dummy_df = all_dummy_df.fillna(mean_cols)#數據清洗,用()中的值代替空值
print(all_dummy_df.isnull().sum().sum())
###############6 smooth numeric cols########################
numeric_cols = all_df.columns[all_df.dtypes != 'object']#選取屬性不是object,即數值型數據
print(numeric_cols)
numeric_col_means = all_dummy_df.loc[:, numeric_cols].mean()#按照括號的索引選取數據,並求均值
numeric_col_std = all_dummy_df.loc[:, numeric_cols].std()
all_dummy_df.loc[:, numeric_cols] = (all_dummy_df.loc[:, numeric_cols] - numeric_col_means) / numeric_col_std
###############7 train model#######################
dummy_train_df = all_dummy_df.loc[train_df.index]
dummy_test_df = all_dummy_df.loc[test_df.index]
print("shape of dummy_train_df:" + str(dummy_train_df))
print("shape of dummy_test_df:" + str(dummy_test_df))
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
X_train = dummy_train_df.values
X_test = dummy_test_df.values
alphas = np.logspace(-3, 2, 50)
test_scores = []
for alpha in alphas:
clf = Ridge(alpha)
test_score = np.sqrt(-cross_val_score(clf, X_train, y_train, cv=10, scoring='neg_mean_squared_error'))
test_scores.append(np.mean(test_score))
plt.plot(alphas, test_scores)
plt.title("Alpha vs CV Error")
plt.show()
from sklearn.ensemble import RandomForestRegressor
max_features = [.1, .3, .5, .7, .9, .99]
test_scores = []
for max_feat in max_features:
clf = RandomForestRegressor(n_estimators=200, max_features=max_feat)
test_score = np.sqrt(-cross_val_score(clf, X_train, y_train, cv=5, scoring='neg_mean_squared_error'))
test_scores.append(np.mean(test_score))
plt.plot(max_features, test_scores)
plt.title("Max Features vs CV Error")
plt.show()
#########################8 stacking#####################
ridge = Ridge(alpha=15)
rf = RandomForestRegressor(n_estimators=200, max_features=.3)
ridge.fit(X_train, y_train)
rf.fit(X_train, y_train)
y_ridge = np.expm1(ridge.predict(X_test))
y_rf = np.expm1(rf.predict(X_test))
y_final = (y_ridge + y_rf)/2
######################9 submission############################
submission_df = pd.DataFrame(data = {'Id':test_df.index, 'SalePrice':y_final})
print(submission_df.head())
