zoukankan      html  css  js  c++  java
  • Pandas数据分析

    Pandas

    pandas 是基于NumPy 的一种工具,该工具是为解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。pandas提供了大量能使我们快速便捷地处理数据的函数和方法。你很快就会发现,它是使Python成为强大而高效的数据分析环境的重要因素之一。

    简介

    Pandas [1] 是python的一个数据分析包,最初由AQR Capital Management于2008年4月开发,并于2009年底开源出来,目前由专注于Python数据包开发的PyData开发team继续开发和维护,属于PyData项目的一部分。Pandas最初被作为金融数据分析工具而开发出来,因此,pandas为时间序列分析提供了很好的支持。 Pandas的名称来自于面板数据(panel data)和python数据分析(data analysis)。panel data是经济学中关于多维数据集的一个术语,在Pandas中也提供了panel的数据类型。

    数据结构

    • Series:一维数组,与Numpy中的一维array类似。二者与Python基本的数据结构List也很相近。Series如今能保存不同种数据类型,字符串、boolean值、数字等都能保存在Series中。
    • Time- Series:以时间为索引的Series。
    • DataFrame:二维的表格型数据结构。很多功能与R中的data.frame类似。可以将DataFrame理解为Series的容器。
    • Panel :三维的数组,可以理解为DataFrame的容器。
    • Panel4D:是像Panel一样的4维数据容器。
    • PanelND:拥有factory集合,可以创建像Panel4D一样N维命名容器的模块。

    数据的读取

    数据读写

    从csv、xlsx、txt等文件格式中读取数据:

    athlete = pd.read_csv('./input/athlete.csv')
    # athlete1 = pd.read_excel('./input/athlete.xlsx')
    # athlete2 = pd.read_csv('./input/athlete.txt',delimiter="	")  #制表符

    查看数据类型和大小

    type(athlete)
    # athlete.shape

    数据的索引与切片

    查看索引列名

    athlete.columns
    # athlete.index
    # athlete.values

    查看部分数据

    athlete.head(1)
    # athlete.tail(3)
    # athlete.sample(3)

    数据索引和切片

    选取一列的三种方式:

    # athlete['Sex']
    # athlete.loc[:,'Sex']  #loc按索引名称切片  用于选取行索引列索引已知
    # athlete.iloc[:,2] #选取某一列  按默认索引(实际位置)切片,不知道列名只知道列的位置时
    # type(athlete['Sex'])  #Series
    # type(athlete[['Sex']])  #DataFrame

    选取一行的两种方式:

    # athlete[2]  #错误
    # athlete.loc[2]
    athlete.iloc[2] #选取某一行

    选取多行或多列:

    # 选取多行或多列
    # athlete.iloc[0:5] #显示前五行 同head()
    # athlete.iloc[:,0:5] #显示前五列
    athlete.iloc[0:5,0:5] #前五列+前五行

    选取某行某列:

    athlete.loc[2,'Sex'] #选取某行某列
    # athlete.iloc[2,2]
    # athlete.loc[2:4,['Sex','Age']] #选取某几行某几列
    # athlete.iloc[2:4,2:4]

    数据的增加删除和修改

    删除某列

    # athlete.drop('Sex',axis=1) #axis=1 ,删除columns,axis=0 指删除index;
    # athlete.head()
    # inplace=False,#默认,不改变原数据,返回新dataframe;
    athlete.drop('Sex',axis=1,inplace=True) 

    删除某行

    # athlete.drop(0,axis=0) #删除某行
    # athlete.head(1)
    athlete.drop(0,axis=0,inplace=True)

    增加一列/行

    #增加一列 insert #增加一行 concat
    athlete['rate'] = athlete['Weight']/athlete['Height']

    更改某个值

    athlete.iloc[2,2] = 18

    更改某一列/行

    # athlete['Weight'] = 100
    athlete.iloc[0] = 0 

    描述性统计

    更直观的概览 describe()

    # athlete.describe()
    # type(athlete.describe())
    # athlete.describe().loc['mean','Age']
    # athlete.describe(include='all')
    athlete.info()

    根据列中不同值分组,统计每组的个数 value_counts()

    # athlete['Age'].value_counts() #除去非空值,每一列中不同值分别出现的次数
    # athlete['Height'].value_counts()
    athlete['Team'].value_counts()
    athlete['Medal'].value_counts()
    # athlete['Medal'].value_counts(dropna=False)
    # type(athlete['Medal'].value_counts(dropna=False))
    # athlete['Medal'].value_counts(dropna=False).index[1]

    某列单独的聚合计算:

    # 某列单独计算
    athlete['Height'].mean()
    # athlete['Height'].max()
    # athlete['Height'].min()

    Pandas绘图

    直方图

    # athlete['Height'].plot(kind='hist')  #频数分布
    %matplotlib inline
    athlete['Age'].plot(kind='hist',color='red',title="Age distribution")
    athlete['Age'].plot(kind='hist',color='red',title="Age distribution").set_xlabel("Age")

    条形图

    # athlete['Medal'].value_counts(dropna=False).plot(kind='bar',rot=360) #离散型的多用条形图
    athlete['Medal'].value_counts().plot(kind='barh')  #水平条形图

    箱线,饼图,散点图

    # athlete['Age'].plot(kind='box')  #箱线图
    # athlete['Age'].value_counts().plot(kind='pie')  #饼图
    athlete.plot(kind="scatter",x='Weight',y='Height')  # 两个变量,散点图

    利用数据进行建模

    分组聚合

    size()value_counts()

    athlete['Sex'].value_counts()
    athlete.groupby('Sex').size()

    按一个键分组:

    # athlete.groupby('Sex')['Height'].mean()
    # athlete.groupby('Sex')['Height'].mean().plot(kind="bar",rot=360)
    # athlete.groupby('Sex')['Age','Height','Weight'].mean()
    athlete.groupby('Sex')['Age','Height','Weight'].mean().plot()
    # athlete.groupby('Sex')['Age','Height','Weight'].agg(['mean','max','min'])

    按多个键分组,层次化索引:

    athlete.groupby(['Year','Season']).size()
    type(athlete.groupby(['Year','Season']).size())
    # athlete.groupby(['Year','Season'])['Age','Height','Weight'].mean()  
    # type(athlete.groupby(['Year','Season'])['Age','Height','Weight'].mean())   #层次化索引
    # athlete.groupby(['Year','Season'])['Age','Height','Weight'].mean().iloc[4,:]

    数据规整

    判断是否为空:

    # athlete.isnull()
    # athlete.notnull()
    athlete.isnull().any()
    athlete['Age'].isnull().value_counts()
    athlete['Height'].isnull().value_counts()

    填充空值:

    athlete['Height'] = athlete['Height'].fillna(athlete['Height'].mean())
    athlete['Weight'] = athlete['Weight'].fillna(athlete['Weight'].mean())

    删除空值:

    athlete = athlete[athlete['Age'].notnull()]
    # athlete['Age'].value_counts(dropna=False)
    # athlete['Medal'].value_counts(dropna=False)  #数据太多,模型跑的时间久;属于不同类别的样本的分布不平衡,过采样
    athlete = athlete[athlete['Medal'].notnull()]

    特征编码:

    #消除差序关系,自动跳过数值型数据
    X = pd.get_dummies(athlete[['Age','Sex','Weight','Height','Team','NOC','Games','Year','Season','City','Sport','Event']])
    y = athlete['Medal']

    数据建模

    划分训练集和数据集:

    from sklearn.model_selection import train_test_split
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,random_state=0)

    模型选择:随机森林:

    from sklearn.ensemble import RandomForestClassifier
    clf = RandomForestClassifier(n_estimators=100)
    clf.fit(X_train,y_train)
    print(clf)

    模型评估:

    from sklearn import metrics
    y_predict = clf.predict(X_test)
    print(metrics.classification_report(y_test, y_predict))
    print(metrics.confusion_matrix(y_test,y_predict))

    准确率:

    metrics.accuracy_score(y_test, y_predict)
  • 相关阅读:
    PHP乘法表
    通过闭包可以返回局部变量
    FZU2125_简单的等式
    FZU2122_又见LKity
    FZU2121_神庙逃亡
    UVA12585_Poker End Games
    UVA12583_Memory Overow
    HDU4647_Another Graph Game
    HDU4646_Laser Beam
    HDU4787_GRE Words Revenge
  • 原文地址:https://www.cnblogs.com/MoooJL/p/14364643.html
Copyright © 2011-2022 走看看