本文共 1957 字,大约阅读时间需要 6 分钟。
Pandas 是 NumPy 的高级接口,提供了更简便的操作方式来处理数值数据。以下是关于 Pandas 数值运算的详细说明。
对于一元运算(如函数与三角函数),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
对于二元运算(如加法和乘法),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() |
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
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/