Pandas常用功能与函数介绍(结合实例,持续更新)
创作时间:
作者:
@小白创作中心
Pandas常用功能与函数介绍(结合实例,持续更新)
引用
CSDN
1.
https://blog.csdn.net/weixin_41770169/article/details/79539232
本文首先介绍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]
房价预测案例
根据给定的训练csv文件,预测给出的测试csv文件中的房价。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 数据导入
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("shape of train_df:" + str(train_df.shape))
print("shape of test_df:" + str(test_df.shape))
# 数据查看
train_df.head()
# 数据创建
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.show()
y_train = np.log1p(train_df.pop('SalePrice'))
print("shape of y_train:" + str(y_train.shape))
# 数据合并
all_df = pd.concat((train_df, test_df), axis=0)
print("shape of all_df:" + str(all_df.shape))
# 数据格式转换
print(all_df['MSSubClass'].dtypes)
all_df['MSSubClass'] = all_df['MSSubClass'].astype(str)
all_df['MSSubClass'].value_counts()
print(all_df['MSSubClass'].value_counts())
# 数据清洗
all_dummy_df = pd.get_dummies(all_df) # one-hot编码
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())
# 数据统计
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
# 模型训练
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()
# 模型融合
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
# 结果提交
submission_df = pd.DataFrame(data = {'Id':test_df.index, 'SalePrice':y_final})
print(submission_df.head())
参考文章:
- Pandas官网
- Pandas官方文档
- Pandas Cheat Sheet -- Python for Data Science
- 10 minutes to Pandas
热门推荐
防伪标签设计技巧,增强品牌辨识度
鼻子起皮怎么办?医生给出专业建议
美国本科药学专业有哪些选择和机会
从零开始建立社交圈:实用建群指南与技巧分享
如何快速分类PCB,工程师必备!
给韩国打电话前面加什么?
刘彻阳谋推恩令:汉武帝的权谋策略与皇权巩固
汉武帝推恩令:削弱诸侯势力的法律创新
新概念模电:负反馈与运放的深入解析
学信网报告编号是什么 如何查询报告编号
入墙式音箱的优势与安装要点:打造隐形的音乐享受
人事专员简历写作指南:六大维度打造高吸引力简历
牛顿和爱因斯坦差别在哪里?
牛顿和爱因斯坦差别在哪里?
虎皮兰的阳光习性(探究虎皮兰对阳光的喜好与影响)
这3种植物“吸甲醛”,比绿萝、吊兰“强10倍”,回家养几盆吧!
埃塞俄比亚咖啡品种74158、74110:数字背后的科学与市场
PA66材料性能参数|深入解析PA66材料性能参数及其应用
揭秘氢氧化镁:化妆品中的多功能成分
深圳⇄珠海30分钟!深珠通道最新信息来了!
国内护理硕士如何成功申请澳洲留学
如何给文竹换盆?用点“小技巧”,蹭蹭冒小芽,疯长不停
扔掉你的阔腿裤吧,太显矮!今秋流行这3条裤子,显高显瘦还百搭
电脑怎么连接打印机设备 添加打印机教程介绍
3 种实用方法:如何为 Windows 11 添加网络打印机
干货 | 膝关节常见体格检查——膝关节力线、髌骨检查、膝周压痛点
工控一体机常见接口类型及应用场景解析
肾功能不全人士适宜饮用的茶饮推荐
如何看待职场“裙带关系”?
中国城市综合发展指标北京连续8年排名首位,上海、深圳、广州进入前四名