博客
关于我
第3章 Pandas数据处理(3.4-3.5)_Python数据科学手册学习笔记
阅读量:84 次
发布时间:2019-02-26

本文共 1957 字,大约阅读时间需要 6 分钟。

Pandas 数值运算方法

Pandas 是 NumPy 的高级接口,提供了更简便的操作方式来处理数值数据。以下是关于 Pandas 数值运算的详细说明。


1. 一元运算(函数与三角函数)

对于一元运算(如函数与三角函数),Pandas 的通用函数会保留索引和列标签。这种特性使得数据的处理更加灵活,特别是在需要结合不同来源数据时,Pandas 能够自动对齐索引,避免了手动处理索引对齐的问题。

示例代码

import pandas as pdimport numpy as nprng = np.random.RandomState(42)ser = pd.Series(rng.randint(0, 10, 4))df = pd.DataFrame(rng.randint(0, 10, (3, 4)), columns=['a', 'b', 'c', 'd'])

结果展示

ser:0    6132    734    dtype: int32df:   a  b  c  d0  6  9  2  61  7  4  3  72  7  2  5  4

2. 二元运算(加法、乘法等)

对于二元运算(如加法和乘法),Pandas 在传递通用函数时会自动对齐两个对象的索引。这种特性使得数据的处理更加简便,尤其是在需要结合不同数据源时。

索引对齐示例

rk = pd.Series({    '湖北': 1234,    '湖南': 3242,    '广东': 3233}, name='人口')mj = pd.Series({    '湖北': 123,    '湖南': 321,    '山东': 21}, name='面积')rk / mj

输出结果

山东        NaN广东        NaN湖北    10.032520湖南    10.099688dtype: float64

索引对齐的含义

  • 结果数组的索引是两个数组的并集。
  • 也可以通过 rk.index | mj.index 查看对齐后的索引。

示例代码

a = pd.Series([2, 4, 6], index=[0, 1, 2])b = pd.Series([1, 3, 5], index=[1, 2, 3])a + b

输出结果

0    NaN1    5.02    9.03    NaNdtype: float64

常用运算符对应的方法

Python 运算符 Pandas 方法
+ add()
- sub(), subtract()
* mul(), multiply()
/ truediv(), div(), divide()
// floordiv()
% mod()
** pow()

3. DataFrame 与 Series 的运算

DataFrame 减去自身的一行数据

rng = np.random.RandomState(42)a = rng.randint(10, size=(3, 4))df = pd.DataFrame(a, columns=['q', 'r', 's', 't'])df - df.iloc[0]

输出结果

q  r   s   t0  0.0  0.0  0.0  0.01  0.0  6.0 -5.0  2.02  1.0  1.0 -4.0  3.0

4. 处理缺失值

Pandas 提供了几种方法来处理缺失值,包括 isnull()notnull()dropna()fillna()

示例代码

data = pd.Series([1, np.nan, 'Hello', None], index=list('abcde'))data.isnull()

输出结果

a    Falseb    Truec    Falsed    Truedtype: bool

填充缺失值

data.fillna(0)

输出结果

a      1.0b    100.0c      2.0d     2.0e      3.0dtype: float64

从前往后填充缺失值

data.fillna(method='ffill')

输出结果

a    1.0b    1.0c    2.0d    2.0e    3.0dtype: float64

从后往前填充缺失值

data.fillna(method='bfill')

输出结果

a    1.0b    2.0c    2.0d    3.0e    3.0dtype: float64

通过上述方法,Pandas 为数据处理提供了强大的工具,能够高效地完成复杂的数值运算和缺失值处理任务。

转载地址:http://gojk.baihongyu.com/

你可能感兴趣的文章
PLC结构体(西门子)
查看>>
PLC编程语言ST文本语法的常用数据类型及变量
查看>>
PLC通讯方式
查看>>
Please install 'webpack-cli' in addition to webpack itself to use the CLI
查看>>
Ploly Dash,更新一个Dash应用程序JJJA上的实时人物
查看>>
Ploly烛台的定制颜色
查看>>
Ploly:如何在Excel中嵌入完全交互的Ploly图形?
查看>>
plotloss记录
查看>>
Plotly (Python) 子图:填充构面和共享图例
查看>>
Plotly 中的行悬停文本
查看>>
Plotly 停用 x 轴排序
查看>>
Plotly 域变量解释(多图)
查看>>
Plotly 绘制表面 3D 未显示
查看>>
Plotly-Dash 存在未知问题并创建“加载依赖项时出错“;通过使用 Python-pandas.date_range
查看>>
Plotly-Dash:如何过滤具有多个数据框列的仪表板?
查看>>
Plotly:如何为 x 轴上的时间序列设置主要刻度线/网格线的值?
查看>>
Plotly:如何从 x 轴删除空日期?
查看>>
Plotly:如何从单条迹线制作堆积条形图?
查看>>
Plotly:如何以 Root 样式绘制直方图,仅显示直方图的轮廓?
查看>>
Plotly:如何使用 Plotly Express 组合散点图和线图?
查看>>