zoukankan      html  css  js  c++  java
  • 数据处理之pandas库

    1. Series对象

      由于series对象很简单,跟数组类似,但多了一些额外的功能,偷个懒,用思维导图表示

      

    2. DaraFrame对象

      DataFrame将Series的使用场景由一维扩展到多维,数据结构跟Excel工作表极为相似,说白了就是矩阵

    1. 定义DataFrame对象

      DataFrame对象的构造分三部分:数据data,行标签index和列标签columns,下面给出三种构造方法

    data = {'color':['blue','green','yellow','red','white'],
            'object':['ball','pen','pencil','paper','mug'],
            'price':[1.2,1.0,0.6,0.9,1.7]}
    #构造DataFrame方法1
    frame1 = pd.DataFrame(data)
    print(frame1)
    #构造DataFrame方法2
    frame2 = pd.DataFrame(data,columns=['object','price'])
    print(frame2)
    #构造DataFrame方法3
    frame3 = pd.DataFrame(data,columns=['object','price'],index=['a','b','c','d','e'])
    print(frame3)

      上面代码中的data可以为字典,ndarray和matrix对象

    2. 选取元素

      (1)获取行标(index)--->frame.index

      (2)获取列标(columns)--->frame.columns

      (3)获取数据结构中的所有元素  --->frame.values 

      (4)获取每一列的元素 --->frame['price']或frame.price

      (5)获取dataframe中的行信息,可以使用ix方法的索引和数组方式或frame的切片方法

        frame.ix[2] --->获取第3行的信息

        frame.ix[[2,4]] --->获取第3行和第5行的信息

        frame[1:3] --->获取索引为1和2的行信息

      (6)获取指定cell元素 --->frame['price'][3]

      (7)根据元素值进行筛选,比如:--->frame[frame < 12]

    3. 赋值

      通过选取元素同样的逻辑就能增加和修改元素

      (1)修改指定元素的值 --->frame['price'][3] = 8.6

      (2)增加新列new,指定每行的值都为12 --->frame['new'] = 12

      (3)更新指定列的内容 --->frame['new'] = [1,2,3,4,5]

        同样也可以使用Series对象为列赋值

    array = np.arange(5)
    series = pd.Series(array,index=['a','b','c','d','e'])
    print(series)
    frame3['new'] = series
    print(frame3)

      输出:

      

    4. 删除指定行和列

      删除指定行和指定列都使用drop函数

      

      例:

    #删除标签为'a'和'b'的行
    frame4 = frame3.drop(['a','b'],axis=0,inplace=False)
    print('删除指定行:
    ',frame4)
    #删除标签为'price'的列
    frame5 = frame3.drop(['price'],axis=1,inplace=False)
    print('删除指定列:
    ',frame5)

      输出:

      

    3. 统计函数

      和:sum(): 

      均值:mean()

      计算多个统计量:describe()

      

      相关性:corr()

      协方差:cov()

    array = np.array([[1,4,3,6],[4,5,6,1],[3,3,1,5],[4,1,6,4]])
    index = ['red','blue','yellow','white']
    columns = ['ball','pen','pencil','paper']
    frame = pd.DataFrame(array,index=index,columns=columns)
    print(frame)

    print(frame.corr())

    print(frame.cov())

    4. 数据筛选

        a   b   c
    0   0   2   4
    1   6   8  10
    2  12  14  16
    3  18  20  22
    4  24  26  28
    5  30  32  34
    6  36  38  40
    7  42  44  46
    8  48  50  52
    9  54  56  58

    (1)单条件筛选

    df[df['a']>30]
    # 如果想筛选a列的取值大于30的记录,但是之显示满足条件的b,c列的值可以这么写
    df[['b','c']][df['a']>30]
    # 使用isin函数根据特定值筛选记录。筛选a值等于30或者54的记录
    df[df.a.isin([30, 54])]

    (2)多条件筛选

      可以使用&(并)与| (或)操作符或者特定的函数实现多条件筛选

    # 使用&筛选a列的取值大于30,b列的取值大于40的记录
    df[(df['a'] > 30) & (df['b'] > 40)]

    (3)索引筛选

    a. 切片操作

      df[行索引,列索引]或df[[列名1,列名2]]

    #使用切片操作选择特定的行
    df[1:4]
    #传入列名选择特定的列
    df[['a','c']]

    b. loc函数

      当每列已有column name时,用 df [ ‘a’ ] 就能选取出一整列数据。如果你知道column names 和index,且两者都很好输入,可以选择 .loc同时进行行列选择。

    In [28]: df.loc[0,'c']
    Out[28]: 4
    
    In [29]: df.loc[1:4,['a','c']]
    Out[29]:
        a   c
    1   6  10
    2  12  16
    3  18  22
    4  24  28
    
    In [30]: df.loc[[1,3,5],['a','c']]
    Out[30]:
        a   c
    1   6  10
    3  18  22
    5  30  34

    c. iloc函数

      如果column name太长,输入不方便,或者index是一列时间序列,更不好输入,那就可以选择 .iloc了,该方法接受列名的index,iloc 使得我们可以对column使用slice(切片)的方法对数据进行选取。这边的 i 我觉得代表index,比较好记点。

    In [35]: df.iloc[0,2]
    Out[35]: 4
    
    In [34]: df.iloc[1:4,[0,2]]
    Out[34]:
        a   c
    1   6  10
    2  12  16
    3  18  22
    
    In [36]: df.iloc[[1,3,5],[0,2]]
    Out[36]:
        a   c
    1   6  10
    3  18  22
    5  30  34
    
    In [38]: df.iloc[[1,3,5],0:2]
    Out[38]:
        a   b
    1   6   8
    3  18  20
    5  30  32

    d. ix函数

      ix的功能更加强大,参数既可以是索引,也可以是名称,相当于,loc和iloc的合体。需要注意的是在使用的时候需要统一,在行选择时同时出现索引和名称, 同样在同行选择时同时出现索引和名称。

    df.ix[1:3,['a','b']]
    Out[41]:
        a   b
    1   6   8
    2  12  14
    3  18  20
    
    In [42]: df.ix[[1,3,5],['a','b']]
    Out[42]:
        a   b
    1   6   8
    3  18  20
    5  30  32
    
    In [45]: df.ix[[1,3,5],[0,2]]
    Out[45]:
        a   c
    1   6  10
    3  18  22
    5  30  34

    e. at函数

      根据指定行index及列label,快速定位DataFrame的元素,选择列时仅支持列名。

    In [46]: df.at[3,'a']
    Out[46]: 18

    f. iat函数

      与at的功能相同,只使用索引参数

    In [49]: df.iat[3,0]
    Out[49]: 18

    5. csv操作

      csv文件内容

    Supplier Name,Invoice Number,Part Number,Cost,Purchase Date
    Supplier X,001-1001,2341,$500.00 ,1/20/14
    Supplier X,001-1001,2341,$500.00 ,1/20/14
    Supplier X,001-1001,5467,$750.00 ,1/20/14
    Supplier X,001-1001,5467,$750.00 ,1/20/14
    Supplier Y,50-9501,7009,$250.00 ,1/30/14
    Supplier Y,50-9501,7009,$250.00 ,1/30/14
    Supplier Y,50-9505,6650,$125.00 ,2002/3/14
    Supplier Y,50-9505,6650,$125.00 ,2002/3/14
    Supplier Z,920-4803,3321,$615.00 ,2002/3/14
    Supplier Z,920-4804,3321,$615.00 ,2002/10/14
    Supplier Z,920-4805,3321,$615.00 ,2/17/14
    Supplier Z,920-4806,3321,$615.00 ,2/24/14

    (1)csv文件读写

      关于read_csv函数中的参数说明参考博客:https://blog.csdn.net/liuweiyuxiang/article/details/78471036

    import pandas as pd
    
    # 读写csv文件
    df = pd.read_csv("supplier_data.csv")
    df.to_csv("supplier_data_write.csv",index=None)

    (2)筛选特定的行

    #Supplier Nmae列中姓名包含'Z',或者Cost列中的值大于600
    print(df[df["Supplier Name"].str.contains('Z')])
    print(df[df['Cost'].str.strip('$').astype(float) > 600])
    print(df.loc[(df["Supplier Name"].str.contains('Z'))|(df['Cost'].str.strip('$').astype(float) > 600.0),:])
    
    #行中的值属于某个集合
    li = [2341,6650]
    print(df[df['Part Number'].isin(li)])
    print(df.loc[df['Part Number'].astype(int).isin(li),:])
    
    #行中的值匹配某个模式
    print(df[df['Invoice Number'].str.startswith("001-")])

     (3)选取特定的列

    #选取特定的列
    #列索引值,打印1,3列
    print(df.iloc[:,1:4:2])
    #列标题打印
    print(df.loc[:,["Invoice Number", "Part Number"]])
    #选取连续的行
    print(df.loc[1:4,:])
  • 相关阅读:
    G450 Ubuntu14 无线网卡解决
    USB设备不能用。提示Windows 无法启动这个硬件设备。 (代码 19)
    帮你选处理器:CPU T9500-p9500-T9400-T9300-p8700对比分析!
    全球各大运营商黑莓ROM官网下载链接汇总
    查看80端口被占用的方法(IIS、apmserv、system)
    Windows 2003 服务器安全设置-批处理 (附参考链接)
    解决Windows时间同步失败问题!系统时间同步设置!
    WinHTTP Web Proxy Auto-Discovery Service
    关于“未使用GUID分区表”无法安装的解决方案
    DataGridView使用技巧六:冻结列或行
  • 原文地址:https://www.cnblogs.com/xiaobingqianrui/p/10572757.html
Copyright © 2011-2022 走看看