- Series
- 索引对齐
- 去除NaN
- DataFrame
- DataFrame与Series运算
| Python运算符 | Pandas方法 | |
|---|---|---|
| + | add() | a.add(b,fill_value=1),为NaN时加1 |
| - | sub()、subtract() | |
| * | mul()、multiply() | |
| / | truediv()、div()、divide() | |
| // | floordiv() | |
| % | mod() | |
| ** | pow() |
import pandas as pd a = pd.Series([1,2,3]) b = pd.Series([4,5,6]) print(a+b) ''' 0 5 1 7 2 9 dtype: int64 '''索引对齐
NaN表示此处没有数
import pandas as pd a = pd.Series([2,4,6],index=[0,1,2]) b = pd.Series([1,3,5],index=[1,2,3]) print(a+b) ''' 0 NaN 1 5.0 2 9.0 3 NaN dtype: float64 '''去除NaN
NaN不是想要的结果,用适当的对象方法代替运算符a.add(b)等价于a+b,也可自定义a或b缺失的数据
# 没有共同的加fill_value,即加0 print(a.add(b,fill_value=0)) ''' 0 2.0 1 5.0 2 9.0 3 5.0 dtype: float64 '''DataFrame
rng = np.random.RandomState(42)
A = pd.DataFrame(rng.randint(0,20,(2,2)),columns=list('AB'))
print(A)
'''
A B
0 6 19
1 14 10
'''
B = pd.DataFrame(rng.randint(0,10,(3,3)),columns=list('BAC'))
print(B)
'''
B A C
0 7 4 6
1 9 2 6
2 7 4 3
'''
print(A+B)
'''
A B C
0 10.0 26.0 NaN
1 16.0 19.0 NaN
2 NaN NaN NaN
'''
fill = A.stack().mean() # 计算A的均值
print(fill) # 12.25
print(A.add(B,fill_value=fill))# 没有共同的加fill,即加12.25
'''
A B C
0 10.00 26.00 18.25
1 16.00 19.00 18.25
2 16.25 19.25 15.25
'''
DataFrame与Series运算
print(df)
'''
Q R S T
0 6 3 7 4
1 6 9 2 6
2 7 4 3 7
'''
print(df-df.iloc[0])
'''
Q R S T
0 0 0 0 0
1 0 6 -5 2
2 1 1 -4 3
'''
print(df.subtract(df['R'],axis=0))
'''
Q R S T
0 3 0 4 1
1 -3 0 -7 -3
2 3 0 -1 3
'''
halfrow = df.iloc[0,::2]
print(halfrow)
'''
Q 6
S 7
Name: 0, dtype: int32
'''
print(df-halfrow)
'''
Q R S T
0 0.0 NaN 0.0 NaN
1 0.0 NaN -5.0 NaN
2 1.0 NaN -4.0 NaN
'''



