pandas DataFrame index (the difference between iloc and loc)

Pandas - the difference between ix vs loc vs iloc

0. DataFrame

  • The construction of DataFrame mainly depends on the following three parameters:

    • data: table data;
    • index: row index;
    • columns: column name;
      • index indexes rows, and columns indexes columns;
    import pandas as pd  
    data = [[1,2,3],[4,5,6]]  
    index = [0,1]  
    columns=['a','b','c']  
    df = pd.DataFrame(data=data, index=index, columns=columns)  

1. loc

  • iloc gets a row by row index:

    >> df.loc[1]
    a    4 
    b    5 
    c    6 
  • If the DataFrame is constructed with indices not integers but characters:

    index = ['d','e']  
    columns=['a','b','c'] 
    df = pd.DataFrame(data=data, index=index, columns=columns)
    
    >> df.loc['d']
  • Index a column:

    >> df.loc['d', ['b', 'c']]  
    >> df.loc[:, ['c']] 

2. iloc

Different from loc, iloc indexes rows by row number, and an error is reported by row index:

  • df.iloc[0:] : index all rows;
  • df.iloc[:, [1]] : index the first column

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325946132&siteId=291194637