pandas之DataFrame方法与函数

1. DataFrame相关方法

1.1 where()

  • where:满足cond条件的保留,其他用other填充

    相关操作代码结果
    查找df大于60的,小于60的填充"不及格"df.where(cond=df>60,other='不及格')在这里插入图片描述
    A列大于60的不变,小于60的将一行都填充为其他df.where(cond=df['A']>60,other='其他')在这里插入图片描述
    A列小于60填充100,B列小于60填充200,其他默认填NaNdf.where(df>60,other=pd.Series(data=[100,200],index=['A','B']),axis=1)在这里插入图片描述
    1行小于60填充100,2行小于60填充200,其他默认填NaNdf.where(df>60,other=pd.Series(data=[100,200],index=[1,2]),axis=0)在这里插入图片描述
  • 代码

    df=pd.DataFrame(data=np.random.randint(0,100,size=(5,4)),columns=list('ABCD'))
    df.where(cond=df>60,other='不及格')
    df.where(cond=df['A']>60,other='其他')
     df.where(df>60,other=pd.Series(data=[100,200],index=['A','B']),axis=1) 
     df.where(df>60,other=pd.Series(data=[100,200],index=[1,2]),axis=0)
    

1.2 mask()

  • mask:不满足con条件的保留,其他用other填充

    相关操作代码结果
    大于60填充为及格df.mask(df>60,other='及格')在这里插入图片描述
    A列符合条件填充100,B列符合条件填充200,C列符合条件填充300,D列符合条件填充400df.mask(df>60,other=pd.Series(data=[100,200,300,400],index=['A','B','C','D']),axis=1)在这里插入图片描述
  • 代码

    df=pd.DataFrame(data=np.random.randint(0,100,size=(5,4)),columns=list('ABCD'))
    df.mask(df>60,other='及格')
    df.mask(df>60,other=pd.Series(data=[100,200,300,400],index=['A','B','C','D']),axis=1)
    

1.3 query()

  • query()方法:条件查询

    相关操作代码结果
    获取A大于60,B大于60的行df.query('A>60 and B>60')在这里插入图片描述
    获取B等于63的行df.query('B==71')在这里插入图片描述
  • 代码

    df=pd.DataFrame(data=np.random.randint(0,100,size=(5,4)),columns=list('ABCD'))
    df.query('A>60 and B>60')
    df.query('B==71')
    

1.4 filter()

  • filter()方法

    • 对行名和列名进行筛选

    • 使用item选择行,列名称,配合axis

    • 使用regex正则表达式,模糊匹配名称

      相关操作代码结果
      获取0,1行df.filter(items=[0,1],axis=0)在这里插入图片描述
      获取列索引包含Bdf.filter(regex='B',axis=1)在这里插入图片描述
      获取以B开头的列名称df.filter(regex='^B',axis=1)在这里插入图片描述
  • 代码

    df=pd.DataFrame(data=np.random.randint(0,100,size=(5,4)),columns=['AA','BB','CB','DB'])
    df.filter(items=[0,1],axis=0)
    df.filter(regex='B',axis=1)
    df.filter(regex='^B',axis=1)
    

2. 聚合函数

函数描述
count不同值的个数
sum求和
mean均值
mad绝对值均值
median中位数
min最小值
max最大值
mode 众数
abs绝对值
prod乘积
std 标准差
var方差
quantile分位数
cumsum累和
cumprod累积
  • 相关代码
    df=pd.DataFrame(data=np.random.randint(0,100,size=(5,4)),columns=['AA','BB','CB','DB'],dtype='float')
    arr1 = df.values
    arr1[1,1]=np.nan   #填充空值
    arr1.sum()  # #有空值为NaN
    np.nansum(arr1)  # #忽略NaN
    df.loc[1,"BB"]=np.nan  #df填充空值
    #DataFrame默认忽略空值,默认每列的和
    df.sum()
    #求所有数的和
    df.sum().sum()
    
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荼靡~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值