3.1 pandas基本操作、生成与索引

本文介绍了pandas数据分析库中的DataFrame结构,包括如何读取数据、查看数据信息、构造DataFrame、基本操作、索引以及删除行和列的方法。例如,使用`pd.read_csv()`读取CSV文件,`hua.head()`展示数据前几列,`hua.set_index()`设置索引,`hua.drop()`删除行或列。
摘要由CSDN通过智能技术生成

pandas数据分析处理库

3.1.1 pandas概述

  1. import pandas as pd
    hua = pd.read_csv(’./data/hua.csv’)#读入的结构为DataFrame
    hua.head() #显示数据的前5列
    hua.head(10) #显示数据的前10列
  2. hua.info() #返回该数据的信息
    hua.index #返回索引范围
    hua.colums #返回每列的列名
    hua.dtypes #返回每列的类型
    hua.values #返回每行的值

3.1.2 DataFrame结构构造

  1. data = {‘country’:[‘aaa’,‘bbb’,‘ccc’],
    ‘population’:[10,11,23]}
    hua = pd.DataFrame(data) #创建了一个DataFrame结构
  2. population = hua[‘population’] #返回hua的population列
    population[:5] #只显示前五行
    population.index
    population.values[:5]

3.1.3 基本操作

  1. DataFrame中的一行或者一列称为series
    hua[‘population’][:5] #显示population的前5列
  2. hua02 = hua.set_index(‘country’) #将country设为索引
  3. population = hua02[‘population’]
    population02 = population+5 #数组数值运算
    population.mean()
    population.max()
    population.min()
  4. hua02.describe() #统计数组内所有数值的信息

3.1.4 索引

  1. hua = pd.read_csv(’./data/hua.csv’)
    hua[‘Age’][:5] #显示Age列的前5行
    hua[[‘Age’,‘Fare’]][:5] #显示Age与Fare列的前5行

  2. loc用label(字符串?)来去定位,iloc用position(数值)来去定位。
    hua.iloc[0] #相当于第一行的数据
    hua.iloc[0:5]
    hua.iloc[0:5,1:3] #要0到5行的数据,每个数据只要第1和2列。

  3. hua02 = hua.set_index(‘Name’) #将Name设为索引
    hua02.loc[‘huaqianmo’]
    hua02.loc[‘huaqianmo’,‘Fare’] #返回索引huaqianmo的Fare数据。
    hua02.loc[‘huaqianmo’:‘liuwen’,:] #返回从索引huaqianmo到liuwen之间的所有数据(行)的所有参数(列)。

  4. hua02.loc[‘huaqianmo’,‘Fare’]=1000 #定位到的数据可以直接进行赋值操作。

  5. bool类型的索引
    hua[‘Fare’]>40 #返回bool数组,Fare列数值大于40的变为True.0
    hua[hua[‘Fare’]>40] #得到索引,并将该索引传回DataFrame中,只返回True的值
    hua[hua[‘Sex’]==‘male’][:5]

    或者:
    hua.loc[hua[‘Sex’]==‘male’,‘Age’].mean() #统计Sex为male的series,并对其Age取平均值。
    (hua[‘Age’]>70).sum() #统计个数

3.1.4 pandas删除行、列

  1. 删除某列或某行数据可以用到pandas提供的方法drop,
    drop方法的用法:drop(labels, axis=0, level=None, inplace=False, errors=‘raise’); – axis为0时表示删除行,axis为1时表示删除列
  2. 删除单行:
    df2=df1.drop(labels=0) # axis默认等于0,即按行删除,这里表示按行删除第0行
  3. 删除多行:
    通过labels来控制删除行或列的个数,如果是删多行/多列,需写成labels=[1,3],不能写成labels=[1:2],用:号会报错。
    删除指定的某几行(非连续的):
    df21=df1.drop(labels=[1,3],axis=0) # axis=0 表示按行删除,删除第1行和第3行
    要删除连续的多行可以用range(),删除连续的多列不能用此方法。df22=df1.drop(labels=range(1,4),axis=0) # axis=0 表示按行删除,删除索引值是第1行至第3行的正行数据
  4. 删除单列:
    df3=df1.drop(labels=‘gender’,axis=1) # axis=1 表示按列删除,删除gender列。
    删除多列,删除指定的某几列:
    df4=df1.drop(labels=[‘gender’,“age”],axis=1) # axis=1 表示按列删除,删除gender、age列
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值