zoukankan      html  css  js  c++  java
  • python pandas (ix & iloc &loc) 的区别

    oc——通过行标签索引行数据
    iloc——通过行号索引行数据
    ix——通过行标签或者行号索引行数据(基于loc和iloc 的混合)
    同理,索引列数据也是如此!

    举例说明:
    1、分别使用loc、iloc、ix 索引第一行的数据:
    (1)loc

    import pandas as pd
    data=[[1,2,3],[4,5,6]]
    index=['a','b']#行号
    columns=['c','d','e']#列号
    df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框

    #print df.loc['a']
    '''
    c 1
    d 2
    e 3
    '''

    print df.loc[0]
    #这个就会出现错误
    '''
    TypeError: cannot do label indexing on <class 'pandas.indexes.base.Index'>
    with these indexers [1] of <type 'int'>

    (2)iloc

    import pandas as pd
    data=[[1,2,3],[4,5,6]]
    index=['a','b']#行号
    columns=['c','d','e']#列号
    df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框

    print df.iloc[0]
    '''
    c 1
    d 2
    e 3
    '''
    print df.iloc['a']
    '''
    TypeError: cannot do positional indexing on <class 'pandas.indexes.base.Index'>
    with these indexers [a] of <type 'str'>

    (3)ix

    import pandas as pd
    data=[[1,2,3],[4,5,6]]
    index=['a','b']#行号
    columns=['c','d','e']#列号
    df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框

    print df.ix[0]
    '''
    c 1
    d 2
    e 3
    '''
    print df.ix['a']
    '''
    c 1
    d 2
    e 3
    '''
    2、分别使用loc、iloc、ix 索引第一列的数据:

    import pandas as pd
    data=[[1,2,3],[4,5,6]]
    index=['a','b']#行号
    columns=['c','d','e']#列号
    df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框

    print df.loc[:,['c']]

    print df.iloc[:,[0]]

    print df.ix[:,['c']]

    print df.ix[:,[0]]
    #结果都为
    '''
    c
    a 1
    b 4
    3、分别使用loc、iloc、ix 索引多行的数据:

    import pandas as pd
    data=[[1,2,3],[4,5,6]]
    index=['a','b']#行号
    columns=['c','d','e']#列号
    df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框

    print df.loc['a':'b']

    print df.iloc[0:1]

    print df.ix['a':'b']

    print df.ix[0:1]
    #结果都为
    '''
    c d e
    a 1 2 3
    b 4 5 6
    4、分别使用loc、iloc、ix 索引多列的数据:

    import pandas as pd
    data=[[1,2,3],[4,5,6]]
    index=['a','b']#行号
    columns=['c','d','e']#列号
    df=pd.DataFrame(data,index=index,columns=columns)#生成一个数据框

    print df.loc[:,'c':'d']

    print df.iloc[:,0:2]

    print df.ix[:,'c':'d']

    print df.ix[:,0:2]
    #结果都为
    '''
    c d
    a 1 2
    b 4 5
    '''

  • 相关阅读:
    编辑器、编译器、文件、IDE等常见概念辨析
    二叉排序树的实现
    模板
    Codeforces Round #690 (Div. 3)
    Educational Codeforces Round 100 (Rated for Div. 2)
    Codeforces 414-B. Mashmokh and ACM(数位dp)
    Codeforces 339D-Xenia and Bit Operations(线段树)
    Educational Codeforces Round 96 (Rated for Div. 2) 题解
    2019-2020 ICPC Northwestern European Regional Programming Contest (NWERC 2019)
    2018-2019 ICPC Northwestern European Regional Programming Contest (NWERC 2018)
  • 原文地址:https://www.cnblogs.com/jeasonit/p/9994864.html
Copyright © 2011-2022 走看看