zoukankan      html  css  js  c++  java
  • Pandas

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

    Pandas基于两种数据类型:series与dataframe。

    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    # 创建Series对象并省略索引
    '''
    index 参数是可省略的,你可以选择不输入这个参数。
    如果不带 index 参数,Pandas 会自动用默认 index 进行索引,类似数组,索引值是 [0, ..., len(data) - 1] '''
    sel = Series([1,2,3,4])
    print(sel)
    # 通常我们会自己创建索引
    # sel = Series(data = [1,2,3,4], index = ['a','b','c','d'])
    sel = Series(data = [1,2,3,4], index = list('abcd'))
    print(sel)
    # 获取内容
    print(sel.values)
    # 获取索引
    print(sel.index)
    # 获取索引和值对
    print(list(sel.iteritems()))
    输出:
    0    1
    1    2
    2    3
    3    4
    dtype: int64
    a    1
    b    2
    c    3
    d    4
    dtype: int64
    [1 2 3 4]
    Index(['a', 'b', 'c', 'd'], dtype='object')
    [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    # 将字典转换为Series
    dict={"red":100,"black":400,"green":300,"pink":900}
    se3=Series(dict)
    print(se3)
    # Series数据获取
    sel = Series(data = [1,2,3,4], index = list('abcd'))
    print(sel)
    # Series对象同时支持位置和标签两种方式获取数据 print('索引下标',sel['c']) print('位置下标',sel[2])
    # 获取不连续的数据
    print('索引下标',sel[['a','c']])
    print('位置下标',sel[[1,3]])
    # 可以使用切片或取数据
    print('位置切片',sel[1:3])# 左包含右不包含
    print('索引切片',sel['b':'d'])# 左右都包含
    # 重新赋值索引的值
    sel.index = list('dcba')
    print(sel)
    # ReIndex重新索引,会返回一个新的Series(调用reindex将会重新排序,缺失值则用NaN填补)
    print(sel.reindex(['b','a','c','d','e']))
    # Drop丢弃指定轴上的项
    se1=pd.Series(range(10,15))
    print(se1)
    print(se1.drop([2,3]))
    
    输出:
    red      100
    black    400
    green    300
    pink     900
    dtype: int64
    a 1 b 2 c 3 d 4 dtype: int64
    索引下标 a 1 c 3 dtype: int64
    位置下标 b 2 d 4 dtype: int64
    位置切片 b 2 c 3 dtype: int64
    索引切片 b 2 c 3 d 4 dtype: int64
    d 1 c 2 b 3 a 4 dtype: int64
    b 3.0 a 4.0 c 2.0 d 1.0 e NaN dtype: float64
    0 10 1 11 2 12 3 13 4 14 dtype: int64
    0 10 1 11 4 14 dtype: int64

     series算术运算操作

    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    '''
    对 Series 的算术运算都是基于 index 进行的。
    我们可以用加减乘除(+ - * /)这样的运算符对两个 Series 进行运算,
    Pandas 将会根据索引 index,对响应的数据进行计算,结果将会以浮点数的形式存储,以避免丢失精度。 如果 Pandas 在两个 Series 里找不到相同的 index,对应的位置就返回一个空值 NaN
    '''
    series1 = pd.Series([1,2,3,4],['London','HongKong','Humbai','lagos'])
    series2 = pd.Series([1,3,6,4],['London','Accra','lagos','Delhi'])
    print(series1-series2)
    print("-"*20)
    print(series1+series2)
    print("-"*20)
    print(series1*series2)
    print("-"*20)
    # 同样也支持numpy的数组运算
    sel = Series(data = [1,6,3,5], index = list('abcd'))
    print(sel[sel>2]) # 布尔数组过滤
    print("-"*20)
    print(sel*2) # 标量乘法
    print("-"*20)
    print(np.square(sel)) # 可以直接加入到numpy的数学函数
    输出:
    Accra       NaN
    Delhi       NaN
    HongKong    NaN
    Humbai      NaN
    London      0.0
    lagos      -2.0
    dtype: float64
    --------------------
    Accra        NaN
    Delhi        NaN
    HongKong     NaN
    Humbai       NaN
    London       2.0
    lagos       10.0
    dtype: float64
    --------------------
    Accra        NaN
    Delhi        NaN
    HongKong     NaN
    Humbai       NaN
    London       1.0
    lagos       24.0
    dtype: float64
    --------------------
    b    6
    c    3
    d    5
    dtype: int64
    --------------------
    a     2
    b    12
    c     6
    d    10
    dtype: int64
    --------------------
    a     1
    b    36
    c     9
    d    25
    dtype: int64

    DateFrame创建

    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    # 1. 创建DataFrame
    # 使用二维数组
    df1 = DataFrame(np.random.randint(0,10,(4,4)),index=[1,2,3,4],columns=['a','b','c','d'])
    print(df1)
    print("-"*20)
    # 使用字典创建(行索引由index决定,列索引由字典的键决定)
    dict={
        'Province': ['Guangdong', 'Beijing', 'Qinghai', 'Fujian'],
        'pop': [1.3, 2.5, 1.1, 0.7],
        'year': [2018, 2018, 2018, 2018]}
    df2=pd.DataFrame(dict,index=[1,2,3,4])
    print(df2)
    print("-"*20)
    # 使用from_dict
    dict2={"a":[1,2,3],"b":[4,5,6]}
    df6=pd.DataFrame.from_dict(dict2)
    print(df6)
    print("-"*20)
    #索引相同的情况下,相同索引的值会相对应,缺少的值会添加NaN
    data = {
    'Name':pd.Series(['zs','ls','we'],index=['a','b','c']), 'Age':pd.Series(['10','20','30','40'],index=['a','b','c','d']), 'country':pd.Series(['中国','日本','韩国'],index=['a','c','b'])
    }
    df = pd.DataFrame(data)
    print(df)
    print("-"*20)
    # to_dict()方法将DataFrame对象转换为字典
    dict = df.to_dict()
    print(dict)
    输出:
       a  b  c  d
    1  2  0  9  0
    2  5  2  5  0
    3  5  5  6  1
    4  6  0  6  0
    --------------------
        Province  pop  year
    1  Guangdong  1.3  2018
    2    Beijing  2.5  2018
    3    Qinghai  1.1  2018
    4     Fujian  0.7  2018
    --------------------
       a  b
    0  1  4
    1  2  5
    2  3  6
    --------------------
      Name Age country
    a   zs  10      中国
    b   ls  20      韩国
    c   we  30      日本
    d  NaN  40     NaN
    --------------------
    {'Name': {'a': 'zs', 'b': 'ls', 'c': 'we', 'd': nan}, 'Age': {'a': '10', 'b': '20', 'c': '30', 'd': '40'}, 'country': {'a': '中国', 'b': '韩国', 'c': '日本', 'd': nan}}

     DateFrame对象常用属性

    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    # dataframe常用属性
    df_dict = {
        'name':['James','Curry','Iversion'],
        'age':['18','20','19'],
        'national':['us','China','us']
    }
    df = pd.DataFrame(data=df_dict,index=['0','1','2'])
    print(df)
    print("-"*20)
    # 获取行数和列数
    print(df.shape)
    print("-"*20)
    # # 获取行索引
    print(df.index.tolist())
    print("-"*20)
    # # 获取列索引
    print(df.columns.tolist())
    print("-"*20)
    # 获取数据的类型
    print(df.dtypes)
    print("-"*20)
    # 获取数据的维度
    print(df.ndim)
    print("-"*20)
    # values属性也会以二维ndarray的形式返回DataFrame的数据
    print(df.values)
    print("-"*20)
    # 展示df的概览
    print(df.info())
    print("-"*20)
    # 显示头几行,默认显示5行
    print(df.head(2))
    print("-"*20)
    # 显示后几行
    print(df.tail(1))
    print("-"*20)
    # 获取DataFrame的列
    print(df['name'])
    print("-"*20)
    #因为我们只获取一列,所以返回的就是一个 Series
    print(type(df['name']))
    print("-"*20)
    # 如果获取多个列,那返回的就是一个 DataFrame 类型:
    print(df[['name','age']])
    输出:
           name age national
    0     James  18       us
    1     Curry  20    China
    2  Iversion  19       us
    --------------------
    (3, 3)
    --------------------
    ['0', '1', '2']
    --------------------
    ['name', 'age', 'national']
    --------------------
    name        object
    age         object
    national    object
    dtype: object
    --------------------
    2
    --------------------
    [['James' '18' 'us']
     ['Curry' '20' 'China']
     ['Iversion' '19' 'us']]
    --------------------
    <class 'pandas.core.frame.DataFrame'>
    Index: 3 entries, 0 to 2
    Data columns (total 3 columns):
    name        3 non-null object
    age         3 non-null object
    national    3 non-null object
    dtypes: object(3)
    memory usage: 96.0+ bytes
    None
    --------------------
        name age national
    0  James  18       us
    1  Curry  20    China
    --------------------
           name age national
    2  Iversion  19       us
    --------------------
    0       James
    1       Curry
    2    Iversion
    Name: name, dtype: object
    --------------------
    <class 'pandas.core.series.Series'>
    --------------------
           name age
    0     James  18
    1     Curry  20
    2  Iversion  19
    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    # dataframe常用属性
    df_dict = {
        'name':['James','Curry','Iversion'],
        'age':['18','20','19'],
        'national':['us','China','us']
    }
    df = pd.DataFrame(data=df_dict,index=['0','1','2'])
    print(df)
    print("-"*20)
    print(type(df[['name','age']]))
    print("-"*20)
    # 获取一行
    print(df[0:1])
    print("-"*20)
    # 取多行
    print(df[1:3])
    print("-"*20)
    # 取多行里面的某一列(不能进行多行多列的选择)
    print(df[1:3][['name','age']])
    print("-"*20)
    # 注意: df[]只能进行行选择,或列选择,不能同时多行多列选择。
    '''
    df.loc 通过标签索引行数据 df.iloc 通过位置获取行数据 '''
    # 获取某一行某一列的数据
    print(df.loc['0','name'])
    print("-"*20)
    # 一行所有列
    print(df.loc['0',:])
    print("-"*20)
    # 某一行多列的数据
    print(df.loc['0',['name','age']])
    print("-"*20)
    # 选择间隔的多行多列
    print(df.loc[['0','2'],['name','national']])
    print("-"*20)
    # 选择连续的多行和间隔的多列
    print(df.loc['0':'2',['name','national']])
    print("-"*20)
    # 取一行
    print(df.iloc[1])
    print("-"*20)
    # 取连续多行
    print(df.iloc[0:2])
    print("-"*20)
    # 取间断的多行
    print(df.iloc[[0,2],:])
    print("-"*20)
    # 取某一列
    print(df.iloc[:,1])
    print("-"*20)
    # 某一个值
    print(df.iloc[1,0])
    print("-"*20)
    # 修改值
    df.iloc[0,0]='panda'
    print(df)
    print("-"*20)
    # dataframe中的排序方法
    df = df.sort_values(by='age',ascending=False) # ascending=False : 降序排列,默认是升序
    print(df)
    输出:
           name age national
    0     James  18       us
    1     Curry  20    China
    2  Iversion  19       us
    --------------------
    <class 'pandas.core.frame.DataFrame'> --------------------
    name age national 0 James 18 us --------------------
    name age national 1 Curry 20 China 2 Iversion 19 us --------------------
    name age 1 Curry 20 2 Iversion 19 --------------------
    James --------------------
    name James age 18 national us Name: 0, dtype: object --------------------
    name James age 18 Name: 0, dtype: object --------------------
    name national 0 James us 2 Iversion us --------------------
    name national 0 James us 1 Curry China 2 Iversion us --------------------
    name Curry age 20 national China Name: 1, dtype: object --------------------
    name age national 0 James 18 us 1 Curry 20 China --------------------
    name age national 0 James 18 us 2 Iversion 19 us --------------------
    0 18 1 20 2 19 Name: age, dtype: object --------------------
    Curry --------------------
    name age national 0 panda 18 us 1 Curry 20 China 2 Iversion 19 us --------------------
    name age national 1 Curry 20 China 2 Iversion 19 us 0 panda 18 us

     dateframe修改index、columns

    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    df1 = pd.DataFrame(np.arange(9).reshape(3, 3), index = ['bj', 'sh', 'gz'], columns=['a', 'b', 'c'])
    print(df1)
    print("-"*20)
    # 修改 df1 的 index
    print(df1.index)
    print("-"*20)
    # 可以打印出print的值,同时也可以为其赋值
    df1.index = ['beijing', 'shanghai', 'guangzhou']
    print(df1)
    print("-"*20)
    # 自定义map函数(x是原有的行列值)
    def test_map(x):
        return x+'_ABC'
    print(df1.rename(index=test_map,columns=test_map))
    print("-"*20)
    # 同时,rename 还可以传入字典,为某个 index 单独修改名称
    df3 = df1.rename(index={'bj':'beijing'}, columns = {'a':'aa'})
    print(df3)
    print("-"*20)
    # 列转化为索引
    df1=pd.DataFrame({'X':range(5),'Y':range(5),'S':list("abcde"),'Z':[1,1,2,2,2]})
    print(df1)
    print("-"*20)
    # 指定一列为索引 (drop=False 指定同时保留作为索引的列)
    result = df1.set_index('S',drop=False)
    result.index.name=None
    print(result)
    输出:
        a  b  c
    bj  0  1  2
    sh  3  4  5
    gz  6  7  8
    --------------------
    Index(['bj', 'sh', 'gz'], dtype='object')
    --------------------
               a  b  c
    beijing    0  1  2
    shanghai   3  4  5
    guangzhou  6  7  8
    --------------------
                   a_ABC  b_ABC  c_ABC
    beijing_ABC        0      1      2
    shanghai_ABC       3      4      5
    guangzhou_ABC      6      7      8
    --------------------
               aa  b  c
    beijing     0  1  2
    shanghai    3  4  5
    guangzhou   6  7  8
    --------------------
       X  Y  S  Z
    0  0  0  a  1
    1  1  1  b  1
    2  2  2  c  2
    3  3  3  d  2
    4  4  4  e  2
    --------------------
       X  Y  S  Z
    a  0  0  a  1
    b  1  1  b  1
    c  2  2  c  2
    d  3  3  d  2
    e  4  4  e  2

     添加数据

    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    # 增加数据
    df1 = pd.DataFrame([['Snow','M',22],['Tyrion','M',32],['Sansa','F',18],['Arya','F',14]],
                       columns=['name','gender','age'])
    # 在数据框最后加上score一列
    df1['score']=[80,98,67,90] # 增加列的元素个数要跟原数据列的个数一样
    print(df1)
    print("-"*20)
    # 在具体某个位置插入一列可以用insert的方法
    #  语法格式:列表.insert(index, obj)
    # index --->对象 obj 需要插入的索引位置。
    #  obj ---> 要插入列表中的对象(列名)
    col_name=df1.columns.tolist()  # 将数据框的列名全部提取出来存放在列表里
    col_name.insert(2,'city') # 在列索引为2的位置插入一列,列名为:city,刚插入时不会有值,整列都是NaN
    df1=df1.reindex(columns=col_name) # DataFrame.reindex() 对原行/列索引重新构建索引值
    print(df1)
    print("-"*20)
    df1['city']=['北京','山西','湖北','澳门']  # 给city列赋值
    print(df1)
    输出:
         name gender  age  score
    0    Snow      M   22     80
    1  Tyrion      M   32     98
    2   Sansa      F   18     67
    3    Arya      F   14     90
    --------------------
         name gender  city  age  score
    0    Snow      M   NaN   22     80
    1  Tyrion      M   NaN   32     98
    2   Sansa      F   NaN   18     67
    3    Arya      F   NaN   14     90
    --------------------
         name gender city  age  score
    0    Snow      M   北京   22     80
    1  Tyrion      M   山西   32     98
    2   Sansa      F   湖北   18     67
    3    Arya      F   澳门   14     90
    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    # 增加数据
    df1 = pd.DataFrame([['Snow','M',22],['Tyrion','M',32],['Sansa','F',18],['Arya','F',14]],
                       columns=['name','gender','age'])
    df1.insert(2,'score',[80,98,67,90])
    print(df1)
    print("-"*20)
    # 插入一行
    row=['111','222','333','444']
    df1.iloc[1]=row
    print(df1)
    print("-"*20)
    # 增加数据
    df1 = pd.DataFrame([['Snow','M',22],['Tyrion','M',32],['Sansa','F',18],['Arya','F',14]],
                       columns=['name','gender','age'])
    print(df1)
    print("-"*20)
    # 先创建一个DataFrame,用来增加进数据框的最后一行
    new=pd.DataFrame({'name':'lisa',
                      'gender':'F',
                      'age':19
                      },index=[0])
    print(new)
    print("-------在原数据框df1最后一行新增一行,用append方法------------")
    f1=df1.append(new,ignore_index=True)
    # ignore_index=False,表示不按原来的索引,从0开始自动递增
    print(f1)
    输出:
         name gender  score  age
    0    Snow      M     80   22
    1  Tyrion      M     98   32
    2   Sansa      F     67   18
    3    Arya      F     90   14
    --------------------
        name gender score  age
    0   Snow      M    80   22
    1    111    222   333  444
    2  Sansa      F    67   18
    3   Arya      F    90   14
    --------------------
         name gender  age
    0    Snow      M   22
    1  Tyrion      M   32
    2   Sansa      F   18
    3    Arya      F   14
    --------------------
       name gender  age
    0  lisa      F   19
    -------在原数据框df1最后一行新增一行,用append方法------------
         name gender  age
    0    Snow      M   22
    1  Tyrion      M   32
    2   Sansa      F   18
    3    Arya      F   14
    4    lisa      F   19
    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    # 插入多行多列
    '''
    objs:合并对象 axis:合并方式,默认0表示按列合并,1表示按行合并 ignore_index:是否忽略索引
    '''
    df1 = pd.DataFrame(np.arange(6).reshape(3,2),columns=['four','five'])
    df2 = pd.DataFrame(np.arange(6).reshape(2,3),columns=['one','two','three'])
    print(df2)
    print("-"*20)
    # # 按行合并
    result = pd.concat([df1,df2],axis=1)
    print(result)
    print("-"*20)
    # 按列合并
    result = pd.concat([df1,df2],axis=0,ignore_index=True)
    print(result)
    print("-"*20)
    # DataFrame的删除
    '''
    lables:要删除数据的标签 axis:0表示删除行,1表示删除列,默认0
    inplace:是否在当前df中执行此操作
    '''
    df2 = pd.DataFrame(np.arange(9).reshape(3,3),columns=['one','two','three'])
    print(df2)
    print("-"*20)
    df3=df2.drop(['one'],axis=1, inplace=True)
    # df3=df2.drop([0,1],axis=0, inplace=False)
    print(df2)
    print("-"*20)
    print(df3)
    输出:
       one  two  three
    0    0    1      2
    1    3    4      5
    --------------------
    /Users/lazy/PycharmProjects/matplotlib/drawing.py:17: FutureWarning: Sorting because non-concatenation axis is not aligned. A future version
    of pandas will change to not sort by default.
    
    To accept the future behavior, pass 'sort=False'.
    
    To retain the current behavior and silence the warning, pass 'sort=True'.
    
      result = pd.concat([df1,df2],axis=0,ignore_index=True)
       four  five  one  two  three
    0     0     1  0.0  1.0    2.0
    1     2     3  3.0  4.0    5.0
    2     4     5  NaN  NaN    NaN
    --------------------
       five  four  one  three  two
    0   1.0   0.0  NaN    NaN  NaN
    1   3.0   2.0  NaN    NaN  NaN
    2   5.0   4.0  NaN    NaN  NaN
    3   NaN   NaN  0.0    2.0  1.0
    4   NaN   NaN  3.0    5.0  4.0
    --------------------
       one  two  three
    0    0    1      2
    1    3    4      5
    2    6    7      8
    --------------------
       two  three
    0    1      2
    1    4      5
    2    7      8
    --------------------
    None

     数据处理

    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    from numpy import nan as NaN
    # 通过**dropna()**滤除缺失数据:
    se1=pd.Series([4,NaN,8,NaN,5])
    print(se1)
    print(se1.dropna())
    print(se1.notnull())
    print(se1.isnull())
    # 通过布尔序列也能滤除:
    print(se1[se1.notnull()])
    输出:
    0 4.0
    1 NaN
    2 8.0
    3 NaN
    4 5.0
    dtype: float64
    0 4.0
    2 8.0
    4 5.0
    dtype: float64
    0 True
    1 False
    2 True
    3 False
    4 True
    dtype: bool
    0 False
    1 True
    2 False
    3 True
    4 False
    dtype: bool

      0 4.0
      2 8.0
      4 5.0
      dtype: float64

    import pandas as pd
    from pandas import Series,DataFrame
    from numpy import nan as NaN
    # 处理DataFrame对象
    df1=pd.DataFrame([[1,2,3],[NaN,NaN,2],[NaN,NaN,NaN],[8,8,NaN]])
    print(df1)
    print("-"*20)
    # 默认滤除所有包含NaN:
    print(df1.dropna())
    print("-"*20)
    # 传入how=‘all’滤除全为NaN的行:
    print(df1.dropna(how='all')) # 默认情况下是how='any',只要有nan就删除
    输出:
         0    1    2
    0  1.0  2.0  3.0
    1  NaN  NaN  2.0
    2  NaN  NaN  NaN
    3  8.0  8.0  NaN
    --------------------
         0    1    2
    0  1.0  2.0  3.0
    --------------------
         0    1    2
    0  1.0  2.0  3.0
    1  NaN  NaN  2.0
    3  8.0  8.0  NaN

    import pandas as pd
    from pandas import Series,DataFrame
    from numpy import nan as NaN
    df1=pd.DataFrame([[1,2,3],[NaN,NaN,2],[NaN,NaN,NaN],[8,8,NaN]])
    print(df1)
    print("-"*20)
    # 传入axis=1滤除列:
    print(df1.dropna(axis=1,how="all"))
    print("-"*20)
    #传入thresh=n保留至少有n个非NaN数据的行:
    print(df1.dropna(thresh=1))
    print("-"*20)
    # 填充缺失数据
    df1=pd.DataFrame([[1,2,3],[NaN,NaN,2],[NaN,NaN,NaN],[8,8,NaN]])
    print(df1)
    print("-"*20)
    # 用常数填充fillna
    print(df1.fillna(0))
    print("-"*20)
    #传入inplace=True直接修改原对象:
    df1.fillna(0,inplace=True)
    print(df1)
    输出:
    0 1 2
    0 1.0 2.0 3.0
    1 NaN NaN NaN
    2 NaN NaN NaN
    3 8.0 8.0 NaN
    --------------------
    0 1 2
    0 1.0 2.0 3.0
    1 NaN NaN NaN
    2 NaN NaN NaN
    3 8.0 8.0 NaN
    --------------------
    0 1 2
    0 1.0 2.0 3.0
    3 8.0 8.0 NaN
    --------------------
    0 1 2
    0 1.0 2.0 3.0
    1 NaN NaN 2.0
    2 NaN NaN NaN
    3 8.0 8.0 NaN
    --------------------
    0 1 2
    0 1.0 2.0 3.0
    1 0.0 0.0 2.0
    2 0.0 0.0 0.0
    3 8.0 8.0 0.0
    --------------------
    0 1 2
    0 1.0 2.0 3.0
    1 0.0 0.0 2.0
    2 0.0 0.0 0.0
    3 8.0 8.0 0.0
    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    from numpy import nan as NaN
    # 填充缺失数据
    df1=pd.DataFrame([[1,2,3],[NaN,NaN,2],[NaN,NaN,NaN],[8,8,NaN]])
    print(df1)
    print("-"*20)
    # 通过字典填充不同的常数
    print(df1.fillna({0:10,1:20,2:30}))
    print("-"*20)
    # 填充平均值
    print(df1.fillna(df1.mean()))
    print("-"*20)
    # 如果只填充一列
    print(df1.iloc[:,1].fillna(5,inplace = True))
    print(df1)
    输出:
         0    1    2
    0  1.0  2.0  3.0
    1  NaN  NaN  2.0
    2  NaN  NaN  NaN
    3  8.0  8.0  NaN
    --------------------
          0     1     2
    0   1.0   2.0   3.0
    1  10.0  20.0   2.0
    2  10.0  20.0  30.0
    3   8.0   8.0  30.0
    --------------------
         0    1    2
    0  1.0  2.0  3.0
    1  4.5  5.0  2.0
    2  4.5  5.0  2.5
    3  8.0  8.0  2.5
    --------------------
    None
         0    1    2
    0  1.0  2.0  3.0
    1  NaN  5.0  2.0
    2  NaN  5.0  NaN
    3  8.0  8.0  NaN
    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    from numpy import nan as NaN
    # 填充缺失数据
    df1=pd.DataFrame([[1,2,3],[NaN,NaN,2],[NaN,NaN,NaN],[8,8,NaN]])
    print(df1)
    print("-"*20)
    # 传入method=” “改变插值方式:
    df2=pd.DataFrame(np.random.randint(0,10,(5,5)))
    df2.iloc[1:4,3]=NaN
    df2.iloc[2:4,4]=NaN
    print(df2)
    print("-"*20)
    #用前面的值来填充ffill 用后面的值来填充bfill
    print(df2.fillna(method='ffill'))
    print("-"*20)
    # 传入limit=” “限制填充行数:
    print(df2.fillna(method='bfill',limit=1))
    print("-"*20)
    # 传入axis=” “修改填充方向:
    print(df2.fillna(method="ffill",limit=1,axis=1))
    输出:
         0    1    2
    0  1.0  2.0  3.0
    1  NaN  NaN  2.0
    2  NaN  NaN  NaN
    3  8.0  8.0  NaN
    --------------------
       0  1  2    3    4
    0  0  0  3  4.0  2.0
    1  2  1  5  NaN  5.0
    2  8  6  3  NaN  NaN
    3  6  5  4  NaN  NaN
    4  9  4  3  5.0  7.0
    --------------------
       0  1  2    3    4
    0  0  0  3  4.0  2.0
    1  2  1  5  4.0  5.0
    2  8  6  3  4.0  5.0
    3  6  5  4  4.0  5.0
    4  9  4  3  5.0  7.0
    --------------------
       0  1  2    3    4
    0  0  0  3  4.0  2.0
    1  2  1  5  NaN  5.0
    2  8  6  3  NaN  NaN
    3  6  5  4  5.0  7.0
    4  9  4  3  5.0  7.0
    --------------------
         0    1    2    3    4
    0  0.0  0.0  3.0  4.0  2.0
    1  2.0  1.0  5.0  5.0  5.0
    2  8.0  6.0  3.0  3.0  NaN
    3  6.0  5.0  4.0  4.0  NaN
    4  9.0  4.0  3.0  5.0  7.0
    
    
    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    from numpy import nan as NaN
    #移除重复数据
    ''' DataFrame中经常会出现重复行,利用duplicated()函数返回每一行判断是否重复的结果(重复则为True) '''
    df1 = pd.DataFrame({'A': [1, 1, 1, 2, 2, 3, 1], 'B': list("aabbbca")})
    print(df1)
    print("-"*20)
    # 判断每一行是否重复(结果是bool值,TRUE代表重复的)
    print(df1.duplicated())
    print("-"*20)
    # 去除全部的重复行
    print(df1.drop_duplicates())
    print("-"*20)
    # # 指定列去除重复行
    print(df1.drop_duplicates(['A']))
    print("-"*20)
    # 保留重复行中的最后一行
    print(df1.drop_duplicates(['A'],keep='last'))
    print("-"*20)
    # 去除重复的同时改变DataFrame对象
    df1.drop_duplicates(['A','B'],inplace=True)
    print(df1)
    输出:
    A B
    0 1 a
    1 1 a
    2 1 b
    3 2 b
    4 2 b
    5 3 c
    6 1 a
    --------------------
    0 False
    1 True
    2 False
    3 False
    4 True
    5 False
    6 True
    dtype: bool
    --------------------
    A B
    0 1 a
    2 1 b
    3 2 b
    5 3 c
    --------------------
    A B
    0 1 a
    3 2 b
    5 3 c
    --------------------
    A B
    4 2 b
    5 3 c
    6 1 a
    --------------------
    A B
    0 1 a
    2 1 b
    3 2 b
    5 3 c
     

     数据合并

    # 使用join合并,着重关注的是行的合并
    import pandas as pd
    df3=pd.DataFrame({'Red':[1,3,5],'Green':[5,0,3]},index=list('abc'))
    df4=pd.DataFrame({'Blue':[1,9,8],'Yellow':[6,6,7]},index=list('cde'))
    print(df3)
    print(df4)
    print("-"*20)
    # 简单合并(默认是left左连接,以左侧df3为基础)
    print(df3.join(df4,how='left'))
    print("-"*20)
    # 右链接
    print(df3.join(df4,how='right'))
    print("-"*20)
    # 外链接
    print(df3.join(df4,how='outer'))
    输出:
    Red Green
    a 1 5
    b 3 0
    c 5 3
    Blue Yellow
    c 1 6
    d 9 6
    e 8 7
    --------------------
    Red Green Blue Yellow
    a 1 5 NaN NaN
    b 3 0 NaN NaN
    c 5 3 1.0 6.0
    --------------------
    Red Green Blue Yellow
    c 5.0 3.0 1 6
    d NaN NaN 9 6
    e NaN NaN 8 7
    --------------------
    Red Green Blue Yellow
    a 1.0 5.0 NaN NaN
    b 3.0 0.0 NaN NaN
    c 5.0 3.0 1.0 6.0
    d NaN NaN 9.0 6.0
    e NaN NaN 8.0 7.0
    # 使用merge,着重关注的是列的合并
    import pandas as pd
    df1=pd.DataFrame({'名字':list('ABCDE'),'性别':['男','女','男','男','女'],'职称':['副教授','讲 师','助教','教授','助教']},index=range(1001,1006))
    df1.columns.name='学院老师'
    df1.index.name='编号'
    print(df1)
    print("-"*20)
    df2=pd.DataFrame({'名字':list('ABDAX'),'课程':['C++','计算机导论','汇编','数据结构','马克思原 理'],'职称':['副教授','讲师','教授','副教授','讲师']},index=[1001,1002,1004,1001,3001])
    df2.columns.name='课程'
    df2.index.name='编号'
    print(df2)
    print("-"*20)
    # 默认下是根据左右对象中出现同名的列作为连接的键,且连接方式是how=’inner’
    print(pd.merge(df1,df2))# 返回匹配的
    print("-"*20)
    # 指定列名合并
    print(pd.merge(df1,df2,on='名字',suffixes=['_1','_2']))# 返回匹配的
    print("-"*20)
    # 连接方式,根据左侧为准
    print(pd.merge(df1,df2,how='left'))
    print("-"*20)
    # 根据右侧为准
    print(pd.merge(df1,df2,how='right'))
    print("-"*20)
    # 所有
    print(pd.merge(df1,df2,how='outer'))
    print("-"*20)
    # 根据多个键进行连接
    print(pd.merge(df1,df2,on=['职称','名字']))
    输出:
    学院老师 名字 性别 职称
    编号
    1001 A 男 副教授
    1002 B 女 讲 师
    1003 C 男 助教
    1004 D 男 教授
    1005 E 女 助教
    --------------------
    课程 名字 课程 职称
    编号
    1001 A C++ 副教授
    1002 B 计算机导论 讲师
    1004 D 汇编 教授
    1001 A 数据结构 副教授
    3001 X 马克思原 理 讲师
    --------------------
    名字 性别 职称 课程
    0 A 男 副教授 C++
    1 A 男 副教授 数据结构
    2 D 男 教授 汇编
    --------------------
    名字 性别 职称_1 课程 职称_2
    0 A 男 副教授 C++ 副教授
    1 A 男 副教授 数据结构 副教授
    2 B 女 讲 师 计算机导论 讲师
    3 D 男 教授 汇编 教授
    --------------------
    名字 性别 职称 课程
    0 A 男 副教授 C++
    1 A 男 副教授 数据结构
    2 B 女 讲 师 NaN
    3 C 男 助教 NaN
    4 D 男 教授 汇编
    5 E 女 助教 NaN
    --------------------
    名字 性别 职称 课程
    0 A 男 副教授 C++
    1 A 男 副教授 数据结构
    2 D 男 教授 汇编
    3 B NaN 讲师 计算机导论
    4 X NaN 讲师 马克思原 理
    --------------------
    名字 性别 职称 课程
    0 A 男 副教授 C++
    1 A 男 副教授 数据结构
    2 B 女 讲 师 NaN
    3 C 男 助教 NaN
    4 D 男 教授 汇编
    5 E 女 助教 NaN
    6 B NaN 讲师 计算机导论
    7 X NaN 讲师 马克思原 理
    --------------------
    名字 性别 职称 课程
    0 A 男 副教授 C++
    1 A 男 副教授 数据结构
    2 D 男 教授 汇编
    # 轴向连接-Concat
    import pandas as pd
    s1=pd.Series([1,2],index=list('ab'))
    s2=pd.Series([3,4,5],index=list('bde'))
    print(s1)
    print(s2)
    print("-"*20)
    print(pd.concat([s1,s2],sort=True))
    # 横向连接
    print("-"*20)
    print(pd.concat([s1,s2],axis=1,sort=True))
    print("-"*20)
    # 用内连接求交集(连接方式,共有’inner’,’left’,right’,’outer’)
    print(pd.concat([s1,s2],axis=1,join='inner',sort=True))
    print("-"*20)
    # 指定部分索引进行连接
    print(pd.concat([s1,s2],axis=1,join_axes=[list('abc')]))
    print("-"*20)
    # 创建层次化索引
    print(pd.concat([s1,s2],keys=['A','B'],sort=True))
    print("-"*20)
    # 当纵向连接时keys为列名
    pd.concat([s1,s2],keys=['A','D'],axis=1,sort=True)
    print("-"*20)
    # 2. DataFrame对象的连接
    df3=pd.DataFrame({'Red':[1,3,5],'Green':[5,0,3]},index=list('abd'))
    df4=pd.DataFrame({'Blue':[1,9],'Yellow':[6,6]},index=list('ce'))
    print(df3)
    print(df4)
    print("-"*20)
    print(pd.concat([df3,df4],sort=True))
    print("-"*20)
    print(pd.concat([df3,df4],axis=1,keys=['A','B'],sort=True))
    print("-"*20)
    # 用字典的方式连接同样可以创建层次化列索引
    print(pd.concat({'A':df3,'B':df4},axis=1,sort=True))
    输出:
    a    1
    b    2
    dtype: int64
    b    3
    d    4
    e    5
    dtype: int64
    --------------------
    a    1
    b    2
    b    3
    d    4
    e    5
    dtype: int64
    --------------------
         0    1
    a  1.0  NaN
    b  2.0  3.0
    d  NaN  4.0
    e  NaN  5.0
    --------------------
    /Users/lazy/PycharmProjects/matplotlib/drawing.py:17: FutureWarning: The join_axes-keyword is deprecated. Use .reindex or .reindex_like on the result to achieve the same functionality.
      print(pd.concat([s1,s2],axis=1,join_axes=[list('abc')]))
       0  1
    b  2  3
    --------------------
         0    1
    a  1.0  NaN
    b  2.0  3.0
    c  NaN  NaN
    --------------------
    A  a    1
       b    2
    B  b    3
       d    4
       e    5
    dtype: int64
    --------------------
    --------------------
       Red  Green
    a    1      5
    b    3      0
    d    5      3
       Blue  Yellow
    c     1       6
    e     9       6
    --------------------
       Blue  Green  Red  Yellow
    a   NaN    5.0  1.0     NaN
    b   NaN    0.0  3.0     NaN
    d   NaN    3.0  5.0     NaN
    c   1.0    NaN  NaN     6.0
    e   9.0    NaN  NaN     6.0
    --------------------
         A          B       
       Red Green Blue Yellow
    a  1.0   5.0  NaN    NaN
    b  3.0   0.0  NaN    NaN
    c  NaN   NaN  1.0    6.0
    d  5.0   3.0  NaN    NaN
    e  NaN   NaN  9.0    6.0
    --------------------
         A          B       
       Red Green Blue Yellow
    a  1.0   5.0  NaN    NaN
    b  3.0   0.0  NaN    NaN
    c  NaN   NaN  1.0    6.0
    d  5.0   3.0  NaN    NaN
    e  NaN   NaN  9.0    6.0

     多层索引

    import numpy as np
    import pandas as pd
    from pandas import Series, DataFrame
    #Series 创建多层索引
    s = Series(np.random.randint(0,150,size=6),index=list('abcdef'))
    print(s)
    print("-"*20)
    s = Series(np.random.randint(0,150,size=6),
    index=[['a','a','b','b','c','c'],['期中','期末','期中','期末','期中','期末']])
    print(s)
    print("-"*20)
    # DataFrame创建多层索引
    df1 = DataFrame(np.random.randint(0,150,size=(6,4)),
                    columns = ['zs','ls','ww','zl'],
                    index = [['python','python','math','math','En','En'],['期中','期末','期中','期 末','期中','期末']])
    
    
    print(df1)
    print("-"*20)
    # 特定结构
    class1=['python','python','math','math','En','En']
    class2=['期中','期末','期中','期末','期中','期末']
    m_index2=pd.MultiIndex.from_arrays([class1,class2])
    df2=DataFrame(np.random.randint(0,150,(6,4)),index=m_index2)
    print(df2)
    print("-"*20)
    class1=['期中','期中','期中','期末','期末','期末']
    class2=['python','math','En','python','math','En']
    m_index2=pd.MultiIndex.from_arrays([class1,class2])
    df2=DataFrame(np.random.randint(0,150,(6,4)),index=m_index2)
    print(df2)
    print("-"*20)
    # product构造
    class1 = ['python', 'math', 'En']
    class2 = ['期中', '期末']
    m_index2 = pd.MultiIndex.from_product([class1, class2])
    df2 = DataFrame(np.random.randint(0, 150, (6, 4)), index=m_index2)
    print(df2)
    输出:
    a     47
    b     77
    c     47
    d     59
    e    118
    f    121
    dtype: int64
    --------------------
    a  期中    121
       期末    109
    b  期中      1
       期末     63
    c  期中     43
       期末     43
    dtype: int64
    --------------------
                 zs   ls   ww   zl
    python 期中    63  115   20  115
           期末    96    5  101   13
    math   期中    16  141   68  121
           期 末   54  107  139  120
    En     期中   147  113   41  117
           期末    35   82   17   43
    --------------------
                0   1    2    3
    python 期中  78  43   17    6
           期末   7  87  132  118
    math   期中  95  45   10  147
           期末  39  95  127    3
    En     期中  52  43   43   35
           期末  51  55    6  121
    --------------------
                 0    1   2    3
    期中 python   48   36   6   67
       math    131   59  60   14
       En        2  106  98    7
    期末 python   48   42  59  107
       math     30  132   7  143
       En       23    2  69    3
    --------------------
                0    1    2    3
    python 期中   2   74  125   23
           期末  96   39   72   58
    math   期中  23  129   24  122
           期末  44   96   27   49
    En     期中  88   61  127   43
           期末  23   84    0   73

    多层索引对象的索引

    import numpy as np
    import pandas as pd
    from pandas import Series, DataFrame
    
    # 多层索引对象的索引操作
    # series
    s = Series(np.random.randint(0,150,size=6),
    index=[['a','a','b','b','c','c'],['期中','期末','期中','期末','期中','期末']])
    print(s)
    print("-"*20)
    # 取一个第一级索引
    print(s['a'])
    # 取多个第一级索引
    print(s[['a','b']])
    # 根据索引获取值
    print(s['a','期末'])
    print("-"*20)
    # loc方法取值
    print(s.loc['a'])
    print(s.loc[['a','b']])
    print(s.loc['a','期末'])
    print("-"*20)
    # iloc方法取值(iloc计算的是最内层索引)
    print(s.iloc[1])
    print(s.iloc[1:4])
    print("-"*20)
    # dataframe
    class1 = ['python', 'math', 'En']
    class2 = ['期中', '期末']
    m_index2 = pd.MultiIndex.from_product([class1, class2])
    df2 = DataFrame(np.random.randint(0, 150, (6, 4)), index=m_index2)
    print(df2)
    print("-"*20)
    # 获取列
    print(df2[0])
    # 一级索引
    print(df2.loc['python'])
    # 多个一级索引
    print(df2.loc[['python','math']])
    # 取一行
    print(df2.loc['python','期末'])
    # 取一值
    print(df2.loc['python','期末'][0])
    print("-"*20)
    # iloc是只取最内层的索引
    print(df2.iloc[0])
    输出:
    a  期中     89
       期末     17
    b  期中     31
       期末    129
    c  期中     25
       期末    125
    dtype: int64
    --------------------
    期中    89
    期末    17
    dtype: int64
    a  期中     89
       期末     17
    b  期中     31
       期末    129
    dtype: int64
    17
    --------------------
    期中    89
    期末    17
    dtype: int64
    a  期中     89
       期末     17
    b  期中     31
       期末    129
    dtype: int64
    17
    --------------------
    17
    a  期末     17
    b  期中     31
       期末    129
    dtype: int64
    --------------------
                 0    1    2    3
    python 期中  134  113   93   82
           期末   17  110   79  143
    math   期中   57   85   60  104
           期末   28   12   74  133
    En     期中   74   47  100  122
           期末   58  105   43   13
    --------------------
    python  期中    134
            期末     17
    math    期中     57
            期末     28
    En      期中     74
            期末     58
    Name: 0, dtype: int64
          0    1   2    3
    期中  134  113  93   82
    期末   17  110  79  143
                 0    1   2    3
    python 期中  134  113  93   82
           期末   17  110  79  143
    math   期中   57   85  60  104
           期末   28   12  74  133
    0     17
    1    110
    2     79
    3    143
    Name: (python, 期末), dtype: int64
    17
    --------------------
    0    134
    1    113
    2     93
    3     82
    Name: (python, 期中), dtype: int64

    赠人玫瑰,手有余香,如果我的文章有幸能够帮到你,麻烦帮忙点下右下角的推荐,谢谢!

    作者: imcati

    出处: https://www.cnblogs.com/imcati/>

    本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接

  • 相关阅读:
    bzoj3670 [Noi2014]动物园
    bzoj2882 工艺
    bzoj3097 Hash Killer I
    bzoj3729 Gty的游戏
    【BZOJ4555】[TJOI&HEOI2016]求和 斯特林数+NTT
    【bzoj4869】[Shoi2017]相逢是问候 线段树+扩展欧拉定理
    【BZOJ1853】[Scoi2010]幸运数字 容斥原理+搜索
    【BZOJ2839】集合计数 容斥原理+组合数
    【BZOJ3622】已经没什么好害怕的了 容斥原理+dp
    【BZOJ3589】动态树 树链剖分+线段树
  • 原文地址:https://www.cnblogs.com/imcati/p/11260809.html
Copyright © 2011-2022 走看看