索引与数据的关系
Series = 索引 + 一维数据
DataFrame = 行列索引 + 二维数据
索引与数据的关系:操作索引即是操作数据
算数运算法则
算术运算根据行列索引,补齐后运算,运算默认产生的浮点数。
补齐时缺项填充NaNa(空值)
二维和一维、一维和零维时广播运算
采用+-*/
符号进行二元运算产生新的对象
df1 = pd.DataFrame(np.arange(12).reshape(3, 4), index=['c1', 'c2', 'c3'], columns=['a', 'b', 'c', 'd'])
a b c d
c1 0 1 2 3
c2 4 5 6 7
c3 8 9 10 11
df2 = pd.DataFrame(np.arange(20).reshape(4, 5), index=['c1', 'c2', 'c3', 'c4'], columns=['a', 'b', 'c', 'd', 'e'])
a b c d e
c1 0 1 2 3 4
c2 5 6 7 8 9
c3 10 11 12 13 14
c4 15 16 17 18 19
加法、乘法
index,columns相同的加减、乘法,不相同的index,columns赋值NaNa
print(df1 + df2)
a b c d e
c1 0.0 2.0 4.0 6.0 NaN
c2 9.0 11.0 13.0 15.0 NaN
c3 18.0 20.0 22.0 24.0 NaN
c4 NaN NaN NaN NaN NaN
乘法
print(df1 * df2)
a b c d e
c1 0.0 1.0 4.0 9.0 NaN
c2 20.0 30.0 42.0 56.0 NaN
c3 80.0 99.0 120.0 143.0 NaN
c4 NaN NaN NaN NaN NaN
数据类型的算术·运算方法形式的运算
方法 | 说明 |
---|---|
.add(df, **argws) | 类型间加法运算, 可选参数 |
.sub(df, **argws) | 类型间减法运算, 可选参数 |
.mul(df, **argws) | 类型间乘法运算, 可选参数 |
.div(df, **argws) | 类型间除法运算, 可选参数 |
加法运算
.add(df, **argws)
, 可选参数
将没有的index, columns 补齐为默认参数再运算
print(df1.add(df2, fill_value=100))
a b c d e
c1 0.0 2.0 4.0 6.0 104.0
c2 9.0 11.0 13.0 15.0 109.0
c3 18.0 20.0 22.0 24.0 114.0
c4 115.0 116.0 117.0 118.0 119.0
乘法运算
.add(df, **argws)
, 可选参数
将没有的index, columns 补齐为默认参数再运算
print(df1.mul(df2, fill_value=0))
a b c d e
c1 0.0 1.0 4.0 9.0 0.0
c2 20.0 30.0 42.0 56.0 0.0
c3 80.0 99.0 120.0 143.0 0.0
c4 0.0 0.0 0.0 0.0 0.0
减法运算
.add(df, **argws)
, 可选参数
减去常数, 每个元素都会减去这个常数, 加减乘除同样
print(df1.sub(1))
a b c d
c1 -1 0 1 2
c2 3 4 5 6
c3 7 8 9 10
不同维度运算
Series、DataFrame运算
df3 = pd.Series(np.arange(3), index=['c1', 'c2', 'c3'])
c1 0
c2 1
c3 2
dtype: int32
每个index元素,减去其对应的元素
DataFrame加减乘除Series, 反之报错
print(df1.sub(df3, axis=0))
a b c d
c1 0 1 2 3
c2 3 4 5 6
c3 6 7 8 9
比较运算法则
比较运算只能比较相同索引的元素,不进行补齐
二维和一维、一维和零维间进行广播计算
采用>、<、>=、<=、==、!=
符号进行的二元运算产生的布尔对象
同维度运算尺寸一致,否则报错
横坐标、纵坐标的数量必须一样多, 否则报错
df4 = pd.DataFrame(np.arange(12, 0, -1).reshape(3, 4), index=['c1', 'c2', 'c3'], columns=['a', 'b', 'c', 'd'])
print(df1 > df4)
a b c d
c1 False False False False
c2 False False False True
c3 True True True True
-
不同维度运算,暂时没搞明白
广播运算,默认在1轴