zoukankan      html  css  js  c++  java
  • Pandas中关于 loc iloc 用法的理解

    转载至:https://blog.csdn.net/w_weiying/article/details/81411257

    loc函数:通过行索引 "Index" 中的具体值来取行数据(如取"Index"为"A"的行)

    iloc函数:通过行号来取行数据(如取第二行的数据)

    本文给出loc、iloc常见的五种用法,并附上详细代码。

    1. 利用loc、iloc提取行数据

    import numpy as np
    import pandas as pd
    #创建一个Dataframe
    data=pd.DataFrame(np.arange(16).reshape(4,4),index=list('abcd'),columns=list('ABCD'))
     
    In[1]: data
    Out[1]: 
        A   B   C   D
    a   0   1   2   3
    b   4   5   6   7
    c   8   9  10  11
    d  12  13  14  15
     
    #取索引为'a'的行
    In[2]: data.loc['a']
    Out[2]:
    A    0
    B    1
    C    2
    D    3
     
    #取第一行数据,索引为'a'的行就是第一行,所以结果相同
    In[3]: data.iloc[0]
    Out[3]:
    A    0
    B    1
    C    2
    D    3

    2. 利用loc、iloc提取列数据

    In[4]:data.loc[:,['A']] #取'A'列所有行,多取几列格式为 data.loc[:,['A','B']]
    Out[4]: 
        A
    a   0
    b   4
    c   8
    d  12
     
    In[5]:data.iloc[:,[0]] #取第0列所有行,多取几列格式为 data.iloc[:,[0,1]]
    Out[5]: 
        A
    a   0
    b   4
    c   8
    d  12
     

    3.利用loc、iloc提取指定行、指定列数据

    In[6]:data.loc[['a','b'],['A','B']] #提取index为'a','b',列名为'A','B'中的数据
    Out[6]: 
       A  B
    a  0  1
    b  4  5
     
    In[7]:data.iloc[[0,1],[0,1]] #提取第0、1行,第0、1列中的数据
    Out[7]: 
       A  B
    a  0  1
    b  4  5
  • 相关阅读:
    pands数据框(DataFrame)02
    mysql 临时表
    【转】Mysql 多表连接查询的执行细节 (一)
    【转】cuckoo hash
    [转]全域哈希
    【转】 bloom filter
    【转】bitmap
    golang 反汇编代码阅读-- defer
    assignment3
    Lecture 12: Visualizing and Understanding
  • 原文地址:https://www.cnblogs.com/loubin/p/11299214.html
Copyright © 2011-2022 走看看