zoukankan      html  css  js  c++  java
  • Pandas基本功能之算术运算、排序和排名

    算术运算和数据对齐

    Series和DataFrame中行运算和列运算有种特征叫做广播

    在将对象相加时,如果存在不同的索引对,则结果的索引就是该索引对的并集。自动的数据对齐操作在不重叠的索引处引入了NA值,NA值在算术运算中过程中传播。

    import pandas as pd
    from pandas import Series
    import numpy as np
    s1 = Series([7.3,-2.5,3.4,1.5],index=['a','c','d','e'])
    s2 = Series([-2.1,3.6,-1.5,4,3.1],index=['a','c','e','f','g'])
    s1+s2
    
    a    5.2
    c    1.1
    d    NaN
    e    0.0
    f    NaN
    g    NaN
    dtype: float64
    

    对于DataFrame,对齐操作会同时发生在行和列上。

    df1 = pd.DataFrame(np.arange(9.).reshape(3,3),columns=['b','c','d'],index=['ohio','texas','colorado'])
    df1
    
    	    b	c	d
    ohio	0.0	1.0	2.0
    texas	3.0	4.0	5.0
    colorado6.0	7.0	8.0
    df2 = pd.DataFrame(np.arange(12.).reshape(4,3),columns=['b','d','e'],index=['utah','ohio','texas','oregon'])
    df2
    
            b	d	e
    utah	0.0	1.0	2.0
    ohio	3.0	4.0	5.0
    texas	6.0	7.0	8.0
    oregon	9.0	10.0	11.0
    
    df1+df2
            b	c	d	e
    coloradoNaN	NaN	NaN	NaN
    ohio	3.0	NaN	6.0	NaN
    oregon	NaN	NaN	NaN	NaN
    texas	9.0	NaN	12.0 NaN
    utah	NaN	NaN	NaN	NaN
    

    在算术方法中填充值

    df1 = pd.DataFrame(np.arange(12.).reshape(3,4),columns=list('abcd'))
    df2 = pd.DataFrame(np.arange(20.).reshape(4,5),columns=list('abcde'))
    df1
    
        a	b	c	d
    0	0.0	1.0	2.0	3.0
    1	4.0	5.0	6.0	7.0
    2	8.0	9.0	10.0	11.0
    df2
    
        a	b	c	d	e
    0	0.0	1.0	2.0	3.0	4.0
    1	5.0	6.0	7.0	8.0	9.0
    2	10.0	11.0	12.0	13.0	14.0
    3	15.0	16.0	17.0	18.0	19.0
    df1+df2
    
        a	b	c	d	e
    0	0.0	2.0	4.0	6.0	NaN
    1	9.0	11.0	13.0	15.0	NaN
    2	18.0	20.0	22.0	24.0	NaN
    3	NaN	NaN	NaN	NaN	NaN
    ### 这里面的fill_value=0不是指填充0,而是填充的值为0加上以前的值
    df1.add(df2,fill_value=0)
        a	b	c	d	e
    0	0.0	2.0	4.0	6.0	4.0
    1	9.0	11.0	13.0	15.0	9.0
    2	18.0	20.0	22.0	24.0	14.0
    3	15.0	16.0	17.0	18.0	19.0
    ### 重新索引的时候,fill_value的值是填充1
    df1.reindex(columns=df2.columns,fill_value=1)
        a	b	c	d	e
    0	0.0	1.0	2.0	3.0	1
    1	4.0	5.0	6.0	7.0	1
    2	8.0	9.0	10.0	11.0	1
    
    灵活的算术方法:
    方法 说明
    add +
    sub -
    div /
    mul *

    DataFrame和Series之间的运算

    这就叫做广播,会传递下去的进行算术运算
    arr = np.arange(12.).reshape(3,4)
    arr
    array([[ 0.,  1.,  2.,  3.],
           [ 4.,  5.,  6.,  7.],
           [ 8.,  9., 10., 11.]])
    arr-arr[0]
    array([[0., 0., 0., 0.],
           [4., 4., 4., 4.],
           [8., 8., 8., 8.]])
    

    dataframe中

    
    frame = pd.DataFrame(np.arange(12.).reshape(4,3),columns=list('bde'),index=['utah','ohio','texas','oregon'])
    frame
            b	d	e
    utah	0.0	1.0	2.0
    ohio	3.0	4.0	5.0
    texas	6.0	7.0	8.0
    oregon	9.0	10.0	11.0
    # 先取utah行
    series=frame.ix['utah']
    b    0.0
    d    1.0
    e    2.0
    Name: utah, dtype: float64
    
    frame-series
    
            b	d	e
    utah	0.0	0.0	0.0
    ohio	3.0	3.0	3.0
    texas	6.0	6.0	6.0
    oregon	9.0	9.0	9.0
    
    #如果某个索引值在DataFrame的列或Series的索引中找不到,则参与运算的两个对象就会被重新索引以形成并集。
    series2 = Series(range(3),index=['b','e','f'])
    series2
    frame+series2
    
            b	d	e	f
    utah	0.0	NaN	3.0	NaN
    ohio	3.0	NaN	6.0	NaN
    texas	6.0	NaN	9.0	NaN
    oregon	9.0	NaN	12.0	NaN
    
    # 如果你希望匹配列且在列上广播,则必须使用算术运算方法,axis = 0 代表列索引,axis=1代表行索引。
    series3 = frame['d']
    utah       1.0
    ohio       4.0
    texas      7.0
    oregon    10.0
    Name: d, dtype: float64
    frame.sub(series3, axis=0)
    
            b	d	e
    utah	-1.0	0.0	1.0
    ohio	-1.0	0.0	1.0
    texas	-1.0	0.0	1.0
    oregon	-1.0	0.0	1.0
    

    函数应用和映射

    apply方法

    
    frame = pd.DataFrame(np.arange(12.).reshape(4,3),columns = list('bde'),index=['utah','ohio','texas','oregon'])
    frame
    
            b	d	e
    utah	0.0	1.0	2.0
    ohio	3.0	4.0	5.0
    texas	6.0	7.0	8.0
    oregon	9.0	10.0	11.0
    # 默认操作列
    f = lambda x:x.max()-x.min()
    frame.apply(f)
    
    b    9.0
    d    9.0
    e    9.0
    dtype: float64
    
    # 指定操作行
    frame.apply(f,axis=1)
    
    utah      2.0
    ohio      2.0
    texas     2.0
    oregon    2.0
    dtype: float64
    
    # 如果都实现不了你要的需求,可以直接写函数
    def f(x):
        return Series([x.min(),x.max()],index=['min','max'])
    frame.apply(f)
    
    	b	d	e
    min	0.0	1.0	2.0
    max	9.0	10.0	11.0
    

    applymap方法

    # 还可以python函数的占位符使用,之所以叫applymap,是因为Series有一个应用于元素级函数的map方法
    format = lambda x: '你好%s' % x
    frame.applymap(format)
            b	d	e
    utah	你好0.0	你好1.0	你好2.0
    ohio	你好3.0	你好4.0	你好5.0
    texas	你好6.0	你好7.0	你好8.0
    oregon	你好9.0	你好10.0	你好11.0
    
    frame['d'].map(format)
    utah       你好1.0
    ohio       你好4.0
    texas      你好7.0
    oregon    你好10.0
    Name: d, dtype: object
    

    排序和排名

    排序sort_index、sort_values

    Series可以进行索引排序,默认进行升序,如果要降序排序,可以sort_index(ascending=False)

    Series按值排序,sort_vlaues()

    obj = Series(range(4),index=['d','c','a','b'])
    obj
    d    0
    c    1
    a    2
    b    3
    dtype: int64
    
    obj.sort_index()
    a    2
    b    3
    c    1
    d    0
    dtype: int64
    
    obj.sort_index(ascending=False)
    d    0
    c    1
    b    3
    a    2
    dtype: int64
    
    obj.sort_values()
    d     1
    c     2
    b     3
    a     4
    dtype: int64
    # 降序
    obj1.sort_values(ascending=False)
    b    3
    a    2
    c    1
    d    0
    dtype: int64
    
    # 在排序时,任何缺失值默认都会被放到Series的末尾
    
    obj2 = Series([4,np.nan,7,np.nan,-2,1])
    obj2.sort_values()
    4   -2.0
    5    1.0
    0    4.0
    2    7.0
    1    NaN
    3    NaN
    dtype: float64
    
    

    DataFrame可以进行索引排序,默认为行索引排序

    frame=pd.DataFrame(np.arange(12).reshape(4,3),index=list('badc'),columns=[2,1,3])
    frame
    
        2	1	3
    b	0	1	2
    a	3	4	5
    d	6	7	8
    c	9	10	11
    # 这里的axis为列排序
    frame.sort_index(axis=1)
        1	2	3
    b	1	0	2
    a	4	3	5
    d	7	6	8
    c	10	9	11
    
    frame.sort_index()
        2	1	3
    a	3	4	5
    b	0	1	2
    c	9	10	11
    d	6	7	8
    
    # 在DataFrame上,你可以将一个或多个列的名字传递给by选项即可达到目的。
    frame1 = pd.DataFrame({'b':[4,7,-3,2],'a':[0,1,0,1]})
    
    frame1
        b	a
    0	4	0
    1	7	1
    2	-3	0
    3	2	1
    
    frame1.sort_index(by='b')
        b	a
    2	-3	0
    3	2	1
    0	4	0
    1	7	1
    frame1.sort_index(by=['a','b'])
    
        b	a
    2	-3	0
    0	4	0
    3	2	1
    1	7	1
    

    排名rank()

    表示在这个数在原来的Series中排第几名,有相同的数,取其排名平均(默认)作为值

    
    在obj中,4和4的排名是第4名和第五名,取平均得4.5。7和7的排名分别是第六名和第七名,则其排名取平均得6.5
    
    obj4 = Series([7,-5,7,4,2,0,4])
    obj4.rank()
    
    0    6.5
    1    1.0
    2    6.5
    3    4.5
    4    3.0
    5    2.0
    6    4.5
    dtype: float64
    
    # 根据值在源数据中出现的顺序进行排名
    obj4.rank(method='first')
    0    6.0
    1    1.0
    2    7.0
    3    4.0
    4    3.0
    5    2.0
    6    5.0
    dtype: float64
    
  • 相关阅读:
    小工具之文件整合
    [JavaWeb基础] 031.dom4j写入xml的方法
    AES128_CBC模式加密
    eatwhatApp开发实战(九)
    [Objective-C] 021 KVC、KVO
    eatwhatApp开发实战(八)
    eatwhatApp开发实战(七)
    [Objective-C] 020_ Block
    eatwhatApp开发实战(六)
    年终总结--我的2019
  • 原文地址:https://www.cnblogs.com/lishi-jie/p/9911012.html
Copyright © 2011-2022 走看看