数据科学三基友之Pandas

作者: 可乐还是百事好 | 来源:发表于2018-11-15 22:32 被阅读1次

    Pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。pandas提供了大量能使我们快速便捷地处理数据的函数和方法。

    Pandas两种数据结构:

    • Series
    # Series主要用于处理一维数据 ,一般情况下通过数组并指定index或者直接通过字典创建 。
    
    import numpy as np
    import pandas as pd
    
    #通过数组,指定索引   允许索引重复
    pd_1 = pd.Series([17,19,20,21],index=["yaqi","caha","xueer","jinpp"])
    #print(pd_1)
    
    
    #通过字典
    pd_2 = pd.Series({"yaqi":17,"caha":19,"xueer":20,"jinpp":21})
    #print(pd_2)
    
    >
    yaqi     17
    caha     19
    xueer    20
    jinpp    21
    dtype: int64
    caha     19
    jinpp    21
    xueer    20
    yaqi     17
    dtype: int64
    
    
    • DataFrame
    #**DataFrame可以处理多维数据 ,既有行索引,也有列索引 。**
    
    import numpy as np
    import pandas as pd
    
    list_3 = [[99,130,79],[100,120,80],[77,130,68],[130,120,88]]
    array_3 = np.array(list_3)
    columns = ['语文','数学','英语']
    index = ['张三','李四','王五','赵六']
    pd_3 = pd.DataFrame(array_3,index=index,columns=columns) 
    
    >
         语文   数学  英语
    张三   99  130  79
    李四  100  120  80
    王五   77  130  68
    赵六  130  120  88
    
    
    • DataFrame的属性
    import numpy as np
    import pandas as pd
    
    
    list_3 = [[99,130,79],[100,120,80],[77,130,68],[130,120,88]]
    array_3 = np.array(list_3)
    columns = ['语文','数学','英语']
    index = ['张三','李四','王五','赵六']
    pd_3 = pd.DataFrame(array_3,index=index,columns=columns) 
    
    print(pd_3.info())      #基本信息
    >
      <class 'pandas.core.frame.DataFrame'>
      Index: 4 entries, 张三 to 赵六
      Data columns (total 3 columns):
      语文    4 non-null int32
      数学    4 non-null int32
      英语    4 non-null int32
      dtypes: int32(3)
      memory usage: 80.0+ bytes
    >
    print(pd_3.head(2))     #前2行数据
    >
           语文   数学  英语
      张三   99  130  79
      李四  100  120  80
    >
    print(pd_3.tail(2))       #后2行数据
    >
           语文   数学  英语
      王五   77  130  68
      赵六  130  120  88
    >
    print(pd_3.index)      #索引
    >
      Index(['张三', '李四', '王五', '赵六'], dtype='object')
    >
    print(pd_3.columns)    #列名
    >
      Index(['语文', '数学', '英语'], dtype='object')
    >
    print(pd_3.values)    #所有的值
    >
      [[ 99 130  79]
       [100 120  80]
       [ 77 130  68]
       [130 120  88]]
    
    
    • DataFrame的 index colunms 以及索引
    import numpy as np
    import pandas as pd
    
    
    list_3 = [[99,130,79],[100,120,80],[77,130,68],[130,120,88]]
    array_3 = np.array(list_3)
    columns = ['语文','数学','英语']
    index = ['张三','李四','王五','赵六']
    pd_3 = pd.DataFrame(array_3,index=index,columns=columns) 
    
    #>>>列
    print(pd_3['语文'])
    #选取某列
    print(pd_3['语文'].values)
    #选取某列得值
    
    ##选取某几列 两个中括号
    print(pd_3[['语文','英语']])
    print(pd_3[['语文','英语']].values)
    #>>>列
    
    #>>>行    loc  iloc 针对于行或者行与列   不能单对列
    #loc 索引行的名称   iloc索引行的位置(和列表的索引相同)
    print(pd_3.loc['张三'])
    #单行名称索引  
    print(pd_3.loc[['张三','李四']])
    #多行名称索引  
    
    print(pd_3.iloc[1])
    print(pd_3.iloc[-1])
    #单行位置索引  
    print(pd_3.iloc[:2])
    print(pd_3.iloc[2:4])
    #单行位置索引  
    #>>>行
    
    print(pd_3.iloc[1,2])   #二行三列的值
    print(pd_3.iloc[:,2])    #第三列的所有值
    print(pd_3.iloc[2:,])    #第三行所有值
    print(pd_3.iloc[[1,3],2])  # 第二行和四行 的第三列
    print(pd_3.iloc[1:3],2)   第二到四行的第三列
    
    print(pd_3.at['张三','数学'])   #根据索引名取值
    

    看完Pandas基本的操作我们通过一个实例来进一步学习 。苦逼的高中生活 ,最让人紧张的莫过于高三的一次次摸底考试 ,下面我们用pandas来简单分析一下n年n班的n次摸底考试 。源代码和数据源

    import random
    import numpy as np
    import pandas as pd
    
    origin_datas = pd.read_csv('origin_grades.csv',encoding="gb2312" )
    #print(len(origin_datas))
    #print(len(origin_datas["身份证"].unique()))  #以身份证来看  查看是否右重复项
    
    drop_datas = origin_datas.drop_duplicates(subset="身份证",keep='first') # 根据身份证一列去重  subset = 某一列 keep=‘first’ 保留重复项的第一个   重置索引
    #print(drop_datas)
    #print(origin_datas)
    
    #>>>>>>>>>>>>>增加一列 文理分科
    test_list = ["文科","理科"]
    class_datas = []
    for i in range(27):
    
        class_data = random.sample(test_list,1)
        class_datas.extend(class_data)
    
    
    array_class = np.array(class_datas)
    
    
    new_datas = drop_datas.copy()  #在原表上新添加一列的话  会报错  所以我们建立一个副本
    
    new_datas["分科"] = array_class
    #new_datas.loc["分科"] = new_datas.columns.insert(8,"分科",array_class)  #指定位置插入
    
    #>>>>>>>>>>>>>计算总分 = 语文 + 数学 + 英语
    #new_datas[['语文','数学','英语']].astype(int)
    
    new_datas["总分"] = new_datas[["语文","数学","英语"]].apply(lambda x: x.sum(), axis=1)
    new_datas["平均分"] = new_datas[["语文","数学","英语"]].apply(lambda x: x.mean(), axis=1).astype(int)
    
    
    
    
    
    
    #>>>>>>>>>>>>>加附加分的总分
    
    def score(grade):
        grade = grade + np.random.randint(0,6)
        return grade
    
    new_datas['附加总分'] = new_datas['总分'].apply(score)    #加上附加分
    
    #>>>>>>>>>>>>>计算各个科目平均成绩
    means = new_datas[['语文','数学','英语','总分','附加总分']].mean().astype(int)
    #print(means)
    
    
    #>>>>>>>>>>>>>条件计算 是否本科上线
    array_new = np.array(new_datas)
    
    result = np.where(array_new[:,-1] > 311,'合格','不合格')
    
    new_datas["结果"] = result
    
    
    #print(new_datas)
    
    
    
    
    
    
    #>>>>>>>>>>>>>分类统计
    info_1 = new_datas.groupby(['性别']).agg({'总分':["sum","mean"]})
    
    info_2 = new_datas.groupby(['性别']).agg({'总分':["sum","mean"],'附加总分':["sum","mean"]})
    
    info_3 = new_datas.groupby(['性别','分科']).agg({'总分':["sum","mean"]})
    
    #print(info_3)
    
    
    #>>>>>>>>>>>>>条件筛选
    
    result_1 = new_datas[(new_datas["分科"] == "文科") & (new_datas["性别"] == '男')] #找出文科班男生的所有数据
    
    #print(result_1)
    
    result_2 = new_datas[(new_datas['性别'] == '女') & (new_datas['总分'] >= 340 )][["姓名","学号"]]   #找出女生过一本线的姓名和学号
    #print(result_2)
    #print(new_datas)
    
    
    
    #>>>>>>>>>>>>>排序
    
    new_datas_sort = new_datas.sort_values("附加总分",ascending=True)  #ascending=True升序降序
    #print(new_datas_sort)
    
    
    #new_datas.to_csv("new_grades.csv",encoding="gb2312")
    
    
    
    
    
    
    
    
    

    相关文章

      网友评论

        本文标题:数据科学三基友之Pandas

        本文链接:https://www.haomeiwen.com/subject/iewufqtx.html