Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How are iloc and loc different?

df = pd.DataFrame({'col1': [1,2,3,4,5], 'col2': ["foo", "bar", "baz", "foobar", "foobaz"]})
  col1  col2
0   1   foo
1   2   bar
2   3   baz
3   4   foobar
4   5   foobaz

df = df.sort_values('col1', ascending = False)
      col1  col2
    4   5   foobaz
    3   4   foobar
    2   3   baz
    1   2   bar
    0   1   foo
    
# value at index location (iloc)
df.iloc[0, 0:2]
col1         5
col2    foobaz
Name: 4, dtype: object
# value at index label (loc)
df.loc[0, 'col1':'col2']
col1      1
col2    foo
Name: 0, dtype: object

Comment

iloc and loc

iloc - default indexes (system generated)
loc - table indexes or we manually given indexes 
Comment

How are iloc and loc different?

>>> s = pd.Series(list("abcdef"), index=[49, 48, 47, 0, 1, 2]) 
49    a
48    b
47    c
0     d
1     e
2     f

>>> s.loc[0]    # value at index label 0
'd'

>>> s.iloc[0]   # value at index location 0
'a'

>>> s.loc[0:1]  # rows at index labels between 0 and 1 (inclusive)
0    d
1    e

>>> s.iloc[0:1] # rows at index location between 0 and 1 (exclusive)
49    a
Comment

PREVIOUS NEXT
Code Example
Python :: how to get confusion matrix in python 
Python :: how to know the python pip module version 
Python :: discord.py mention user 
Python :: for loop with enumerate python 
Python :: remove all rows with at least one zero pandas 
Python :: show all rows for dataframe 
Python :: how call module in the same directory 
Python :: pyspark print a column 
Python :: how to declare a variable in python 
Python :: label change in tkinter 
Python :: how to make a list a string 
Python :: python count occurrences of an item in a list 
Python :: pandas unique values to list 
Python :: Roman to integer with python 
Python :: python b before string 
Python :: run for loop inside pdb 
Python :: kruskal python implementation 
Python :: add column in spark dataframe 
Python :: how to make an empty variable in python 
Python :: check if element in list python 
Python :: how to power in python 
Python :: python to mac executable 
Python :: python print string name in pattern 
Python :: run in another thread decorator 
Python :: read file csv in python 
Python :: How to select parts of a numpy array 
Python :: python get zip file size 
Python :: user defined functions python 
Python :: python integer to string 
Python :: python iterating through a string 
ADD CONTENT
Topic
Content
Source link
Name
5+1 =