pandas数据分析处理库
3.1.1 pandas概述
- import pandas as pd
hua = pd.read_csv(’./data/hua.csv’)#读入的结构为DataFrame
hua.head() #显示数据的前5列
hua.head(10) #显示数据的前10列 - hua.info() #返回该数据的信息
hua.index #返回索引范围
hua.colums #返回每列的列名
hua.dtypes #返回每列的类型
hua.values #返回每行的值
3.1.2 DataFrame结构构造
- data = {‘country’:[‘aaa’,‘bbb’,‘ccc’],
‘population’:[10,11,23]}
hua = pd.DataFrame(data) #创建了一个DataFrame结构 - population = hua[‘population’] #返回hua的population列
population[:5] #只显示前五行
population.index
population.values[:5]
3.1.3 基本操作
- DataFrame中的一行或者一列称为series
hua[‘population’][:5] #显示population的前5列 - hua02 = hua.set_index(‘country’) #将country设为索引
- population = hua02[‘population’]
population02 = population+5 #数组数值运算
population.mean()
population.max()
population.min() - hua02.describe() #统计数组内所有数值的信息
3.1.4 索引
-
hua = pd.read_csv(’./data/hua.csv’)
hua[‘Age’][:5] #显示Age列的前5行
hua[[‘Age’,‘Fare’]][:5] #显示Age与Fare列的前5行 -
loc用label(字符串?)来去定位,iloc用position(数值)来去定位。
hua.iloc[0] #相当于第一行的数据
hua.iloc[0:5]
hua.iloc[0:5,1:3] #要0到5行的数据,每个数据只要第1和2列。 -
hua02 = hua.set_index(‘Name’) #将Name设为索引
hua02.loc[‘huaqianmo’]
hua02.loc[‘huaqianmo’,‘Fare’] #返回索引huaqianmo的Fare数据。
hua02.loc[‘huaqianmo’:‘liuwen’,:] #返回从索引huaqianmo到liuwen之间的所有数据(行)的所有参数(列)。 -
hua02.loc[‘huaqianmo’,‘Fare’]=1000 #定位到的数据可以直接进行赋值操作。
-
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删除行、列
- 删除某列或某行数据可以用到pandas提供的方法drop,
drop方法的用法:drop(labels, axis=0, level=None, inplace=False, errors=‘raise’); – axis为0时表示删除行,axis为1时表示删除列 - 删除单行:
df2=df1.drop(labels=0) # axis默认等于0,即按行删除,这里表示按行删除第0行 - 删除多行:
通过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行的正行数据 - 删除单列:
df3=df1.drop(labels=‘gender’,axis=1) # axis=1 表示按列删除,删除gender列。
删除多列,删除指定的某几列:
df4=df1.drop(labels=[‘gender’,“age”],axis=1) # axis=1 表示按列删除,删除gender、age列