
十分钟入门 Pandas
发布日期:2021-05-08 06:30:49
浏览次数:17
分类:精选文章
本文共 7365 字,大约阅读时间需要 24 分钟。
Pandas 是一个强大的数据处理库,基于 NumPy 提供高效操作大型数据集的工具。以下是关于 Pandas 的详细介绍,包括安装、数据类型、操作方法等内容。
安装
安装 Pandas 可以通过以下命令执行:
pip install pandas
数据类型
Pandas 提供了多种数据类型来处理数据,主要包括 Series、DataFrame 和 Panel。
Series
Series 是一种一维数组类型,类似于带标签的 NumPy 数组。每个元素都有一个标签,可以是数字或字符。
定义:
Series
是一维数组类型,带有标签,适合存储一维数据。 关键点:
- 均匀数据:数据分布一致。
- 尺寸大小不变:数据大小保持一致。
- 数据值可变:数据类型和值可以更改。
示例:
import pandas as pdseri = pd.Series([1, 3, 5, np.nan, 9, 10])print(seri)
DataFrame
DataFrame 是一种二维、表格型的数组结构,支持多种数据类型,并且每个轴都有标签。它可以看作是 Series 的字典。
定义:
DataFrame
是一种二维、表格型的数组结构,适合存储多种类型的数据。 关键点:
- 异构数据:支持多种数据类型。
- 大小可变:行和列的数量可以变化。
- 数据值可变:数据类型和值可以改变。
功能特点:
- 支持对行和列执行算术运算。
- 每个轴都有标签。
示例:
import pandas as pdimport numpy as npdf = pd.DataFrame(np.random.randn(10, 4), index=pd.date_range('20181215', periods=10), columns=list('ABCD'))print(df.head())
Panel
Panel 是一种三维数组结构,大小可变,适合处理更高维的数据。
定义:
Panel
是一种三维数组结构,适合存储更高维的数据。 关键点:
- 异构数据:支持多种数据类型。
- 大小可变:行和列的数量可以变化。
- 数据值可变:数据类型和值可以改变。
示例:
import pandas as pddata = np.random.rand(3, 4, 5)print(pd.Panel(data))
三者区别与共性
- 可变性:三者的值都是可变的,除了 Series 之外,大小也是可变的。
- 容器关系:
Panel
是DataFrame
的容器,DataFrame
是Series
的容器。
如何使用 Pandas
创建对象
import pandas as pdimport numpy as npimport matplotlib.pyplot as plt# 创建 Seriesseri = pd.Series([1, 3, 5, np.nan, 9, 10])print(seri)# 创建 DataFramedates = pd.date_range('20181215', periods=10)df = pd.DataFrame(np.random.randn(10, 4), index=dates, columns=list('ABCD'))print(df.head())
数据访问
# 查看数据print('All:\n', df.head())print('前三行:\n', df.head(3))print('后三行:\n', df.tail(3))# 查看索引和列print('index:\n', df.index)print('col:\n', df.columns)print('values:\n', df.values)print('描述:\n', df.describe())print('转置:\n', df.T)
数据操作
# 按标签选择print('df['A']:\n', df['A'])# 位置选择print('df[0:3]:\n', df[0:3])# 根据标签选择print('df[dates[0]]:\n', df.loc[dates[0]])print('df[:, ['A', 'B']]:\n', df.loc[:, ['A', 'B']])# 获取特定值print('df.at[dates[0], 'A']:\n', df.at[dates[0], 'A'])# 位置选择print('df.iloc[3]:\n', df.iloc[3])print('df.iloc[3:5, 0:2]:\n', df.iloc[3:5, 0:2])# 布尔索引print('df[df.A > 0]:\n', df[df.A > 0])
描述性统计
# 求和print('sum:\n', df.sum())# 均值print('avg:\n', df.mean())# 标准差print('std:\n', df.std())# 非空观测数量print('count:\n', df.count())# 中位数print('median:\n', df.median())# 模值print('mode:\n', df.mode())# 累计总和print('cumsum:\n', df.cumsum())# 统计信息摘要print('describe:\n', df.describe(include='all'))
函数应用
def adder(elem1, elem2): return elem1 + elem2# 通过 pipe 函数应用dataFrame = pd.DataFrame(np.random.randn(10,3), columns=['col1', 'col2', 'col3'])dataFrame.pipe(adder, 10)print('pipe:\n', dataFrame.pipe(adder, 10))# 行或列函数应用:applyprint('apply:\n', dataFrame.apply(np.median))# 元素函数应用:applymapprint('map:\n', dataFrame['col1'].map(lambda x: x * 100))print('applymap:\n', dataFrame.apply(lambda x: x * 100))
重建索引
# 重建索引与其他对象对齐df1 = pd.DataFrame(np.random.randn(10,3), columns=['col1', 'col2', 'col3'])df2 = pd.DataFrame(np.random.randn(7,3), columns=['col1', 'col2', 'col3'])# reindx_likedf1 = df1.reindex_like(df2)print('reindex_like:\n', df1)# 前向填充print('ffill:\n', df2.reindex_like(df1, method='ffill'))# 向后填充print('backfill:\n', df2.reindex_like(df1, method='bfill'))# 填充限制print('limit:\n', df2.reindex_like(df1, method='nearest', limit=2))# 重命名df1.rename(columns={'col1': 'c1', 'col2': 'c2'})
迭代
# 迭代 itemsfor key, value in dataFrame.iteritems(): print(key, value)# 迭代 rowsfor row_index, row in dataFrame.iterrows(): print(row_index, row)# 迭代 rows 返回元祖for row in dataFrame.itertuples(): print(row)
排序
unsorted_df = pd.DataFrame(np.random.randn(10,2), index=[1,4,6,2,3,5,9,8,0,7], columns=['col2', 'col1'])print(unsorted_df)# 按标签排序print('sort_index:\n', unsorted_df.sort_index(ascending=False))# 按值排序print('sort_values:\n', unsorted_df.sort_values(by='col2'))# 排序算法print('sort algorithm:\n', unsorted_df.sort_index(kind='heapsort'))
字符串和文本数据
# lower() 将字符串转换为小写# upper() 将字符串转换为大写# len() 计算字符串长度# strip() 删除两侧空格# split(' ') 用给定的模式拆分字符串# cat(sep=' ') 用给定的分隔符连接字符串# get_dummies() 返回单热编码的 DataFramestrings = pd.Series(['Tim ', ' Rick', 'Joson', 'Albert'])print('get_dummies:\n', strings.str.get_dummies())# contains(pattern) 检查是否包含子字符串# replace(a,b) 将 a 替换为 b# repeat(value) 重复每个元素指定次数# count(pattern) 返回模式出现的总次数# startswith(pattern) 检查是否以模式开始# endswith(pattern) 检查是否以模式结束# find(pattern) 返回模式第一次出现的位置# findall(pattern) 返回模式所有出现的列表print('findall:\n', strings.str.findall('e'))# swapcase() 变换大小写# islower() 检查是否所有字符都是小写# isupper() 检查是否所有字符都是大写# isnumeric() 检查是否所有字符都是数字print('isnumeric:\n', strings.str.isnumeric())
选项和自定义
# 获取选项值print('display max rows:', pd.get_option('display.max_rows'))print('display max columns:', pd.get_option('display.max_columns'))# 设置选项pd.set_option('display.max_rows', 90)print('display max rows: ', pd.get_option('display.max_rows'))# 重置选项pd.reset_option('display.max_rows')print('display max rows: ', pd.get_option('display.max_rows'))# 描述选项pd.describe_option('display.max_rows')# 上下文管理器with pd.option_context('display.max_rows', 10): print(pd.get_option('display.max_rows')) print(pd.get_option('display.max_columns')) print(pd.get_option('display.max_colwidth')) print(pd.get_option('display.precision')) print(pd.get_option('display.expand_frame_repr'))
索引与数据选择
dataFrame = pd.DataFrame(np.random.randn(10,4), columns=['A', 'B', 'C', 'D'])print(dataFrame.ix[:5])
统计函数
# pct_change() 比较每个元素与前一个元素df = pd.DataFrame(np.random.randn(5,2))print('pct_change:\n', df.pct_change())# 协方差seri1 = pd.Series(np.random.randn(10))seri2 = pd.Series(np.random.randn(30))print('cov:\n', seri1.cov(seri2))# 相关性frame = pd.DataFrame(np.random.randn(20,5), columns=['a', 'b', 'c', 'd', 'e'])print('相关性:\n', frame['a'].corr(frame['c']))
合并/连接
left = pd.DataFrame({ 'id': [1, 2, 3, 4, 5], 'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'], 'subject_id': ['sub1', 'sub2', 'sub4', 'sub6', 'sub5']})right = pd.DataFrame({ 'id': [1, 2, 3, 4, 5], 'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'], 'subject_id': ['sub2', 'sub4', 'sub3', 'sub6', 'sub5']})left_merge = pd.merge(left, right, on='subject_id', how='left')right_merge = pd.merge(left, right, on='subject_id', how='right')outer_merge = pd.merge(left, right, on='subject_id', how='outer')inner_merge = pd.merge(left, right, on='subject_id', how='inner')print('left:\t', left_merge)print('right:\t', right_merge)print('outer:\t', outer_merge)print('inner:\t', inner_merge)
级联
one = pd.DataFrame({ 'Name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'], 'subject_id': ['sub1', 'sub2', 'sub4', 'sub6', 'sub5'], 'Marks_scored': [98, 90, 87, 69, 78]}, index=[1, 2, 3, 4, 5])two = pd.DataFrame({ 'Name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'], 'subject_id': ['sub2', 'sub4', 'sub3', 'sub6', 'sub5'], 'Marks_scored': [89, 80, 79, 97, 88]}, index=[1, 2, 3, 4, 5])str_concat = pd.concat([one, two], ignore_index=True)print('级联:\n', str_concat)
时间序列
# 获取当前时间print('time now:\n', pd.datetime.now())# 创建时间戳print('创建时间戳:\n', pd.Timestamp('2018-11-11'))# 转换为时间戳print('转换时间戳:\n', pd.to_datetime(['2018/11/23', '2010.12.31', None]))# 改变时间频率print('改变频率:\n', pd.date_range("12:00", "19:59", freq="H").time)# 时间差print('时间差:\n', pd.Timedelta('60 days 11 hours 33 minutes 30 seconds'))
绘图
df = pd.DataFrame(np.random.randn(10,5), index=pd.date_range('2018/12/16', periods=10), columns=list('ABCDE'))df.plot()df.plot.bar()df.plot.hist()df.boxplot()plt.show()
IO 工具
# 读取文件file = pd.read_csv('read.csv')print(file)
通过以上内容,可以看到 Pandas 提供了丰富的功能和方法,适用于数据分析和操作。从基本的数据类型到高级的数据处理和可视化,Pandas 都能满足需求。
发表评论
最新留言
关注你微信了!
[***.104.42.241]2025年04月07日 11时32分57秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
深入浅出访问者模式
2019-03-06
深入探索Android热修复技术原理读书笔记 —— 热修复技术介绍
2019-03-06
百度前端技术学院task16源代码
2019-03-06
解析js中( ( ) { } ( ) )的含义
2019-03-06
js设计模式总结5
2019-03-06
Python大神编程常用4大工具,你用过几个?
2019-03-06
一文带你了解图神经网络
2019-03-06
9个常用ES6特性归纳(一般用这些就够了)
2019-03-06
3D渲染集群,你了解多少?
2019-03-06
除了方文山,用TA你也能帮周杰伦写歌词了
2019-03-06
关于GO语言,这篇文章讲的很明白
2019-03-06
华为云FusionInsight湖仓一体解决方案的前世今生
2019-03-06
大数据处理黑科技:揭秘PB级数仓GaussDB(DWS) 并行计算技术
2019-03-06
C++调用Go方法的字符串传递问题及解决方案
2019-03-06
云原生2.0时代下,DevOps实践如何才能更加高效敏捷?
2019-03-06
技巧收藏|10个JavaScript常用数组操作方法
2019-03-06
两种端到端通用目标检测方法
2019-03-06
云小课 | 守护网络安全不是问题,iptables的四表五链为你开启“八卦阵”
2019-03-06
LiteOS内核源码分析:任务栈信息
2019-03-06
23种设计模式之迭代器模式
2019-03-06