栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Pandas运算

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Pandas运算

文章目录
  • 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()
Series
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
'''
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/870203.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号