pandas常用功能与函数介绍(结合实例,持续更新)

您所在的位置:网站首页 access常用函数示例 pandas常用功能与函数介绍(结合实例,持续更新)

pandas常用功能与函数介绍(结合实例,持续更新)

2024-07-07 13:20| 来源: 网络整理| 查看: 265

 

本文首先介绍Pandas常用功能及函数,最后通过实例举例说明。

 

一、常用功能及函数简介

包导入

一般我们需要做如下导入,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 npimport pandas as pdfrom 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 Ridgefrom sklearn.model_selection import cross_val_score X_train = dummy_train_df.valuesX_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 RandomForestRegressormax_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())


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3