5.2.4算术运算和数据对齐
#算术运算和数据对齐
import pandas as pd
import numpy as np
s1=pd.Series([7.3,-2.5,3.4,1.5],index=["a","c","d","e"])
s2=pd.Series([-2.1,3.6,-1.5,4,3.1],index=["a","c","e","f","g"])
#print(s1+s2)
df1=pd.DataFrame(np.arange(9).reshape(3,3),columns=list("bcd"),index=["Ohio",'Texas','Colorado'])
df2=pd.DataFrame(np.arange(12).reshape(4,3),columns=list("bde"),index=["Utah","Ohio",'Texas','Oregon'])
#print(df1+df2)#对齐操作会同时发生在行和列上
#print(pd.DataFrame({"A":[1,2]})+pd.DataFrame({"B":[3,4]}))#没有共用行或列相加返回值全为空
#带有填充值的算术方法
dp1=pd.DataFrame(np.arange(12).reshape(3,4),columns=list("abcd"))
dp2=pd.DataFrame(np.arange(20).reshape(4,5),columns=list("abcde"))
dp2.loc[1,"b"]=np.nan
print(dp1+dp2)
dp1.add(dp2, fill_value=0)#add方法用传入值替换运算中的缺失值(在我电脑上失效了,可以看下有什么问题)
#print(dp2)
#print(1/dp1)#取倒数
#print(dp1.rdiv(1))#被1除?一个意思
#print(dp1.reindex(columns=dp2.columns,fill_value=0))#重建索引,用fill_value填充
#DataFrame与Series的运算
arr=np.arange(12.).reshape((3,4))
#print(arr[0])
#print(arr-arr[0])#每一行都实行,即广播机制
frame=pd.DataFrame(np.arange(12.).reshape(4,3),columns=list("bde"),index=["Utah","Ohio",'Texas','Oregon'])
series=frame.iloc[0]#取第一行的值
#print(frame-series)#逐行广播
series2=pd.Series(np.arange(3),index=list("bef"))
#print(frame+series2)#会取两个索引的并集重建索引,但不是两方都有的索引下显示NAN
series3=frame["d"]
print(series3)
frame.sub(series3,axis="index")#进行列广播