DataFrame loc vs. iloc



examples/pandas/planets_loc_vs_iloc.py
import sys
import pandas as pd

filename = "planets.csv"
if len(sys.argv) == 2:
    filename = sys.argv[1]

df = pd.read_csv(filename)
print(df)
print()

print(df.loc[3:6])   # by values (here we start from the row where the index column == 3
print()

print(df.iloc[3:6])  # by index (here we start from the 3rd row)
print()

sorted_df = df.sort_values('Planet name', ascending=True)
print(sorted_df)
print()

print(sorted_df.loc[3:6])
print()

print(sorted_df.iloc[3:6])
print()

print('-------')

print(sorted_df.loc[2:4])
print()

print(sorted_df.iloc[2:4])
print()

   Planet name  Distance (AU)        Mass
0      Mercury           0.40    0.055000
1        Venus           0.70    0.815000
2        Earth           1.00    1.000000
3         Mars           1.50    0.107000
4        Ceres           2.77    0.000150
5      Jupiter           5.20  318.000000
6       Saturn           9.50   95.000000
7       Uranus          19.60   14.000000
8      Neptune          30.00   17.000000
9        Pluto          39.00    0.002180
10      Charon          39.00    0.000254

  Planet name  Distance (AU)       Mass
3        Mars           1.50    0.10700
4       Ceres           2.77    0.00015
5     Jupiter           5.20  318.00000
6      Saturn           9.50   95.00000

  Planet name  Distance (AU)       Mass
3        Mars           1.50    0.10700
4       Ceres           2.77    0.00015
5     Jupiter           5.20  318.00000

   Planet name  Distance (AU)        Mass
4        Ceres           2.77    0.000150
10      Charon          39.00    0.000254
2        Earth           1.00    1.000000
5      Jupiter           5.20  318.000000
3         Mars           1.50    0.107000
0      Mercury           0.40    0.055000
8      Neptune          30.00   17.000000
9        Pluto          39.00    0.002180
6       Saturn           9.50   95.000000
7       Uranus          19.60   14.000000
1        Venus           0.70    0.815000

  Planet name  Distance (AU)      Mass
3        Mars            1.5   0.10700
0     Mercury            0.4   0.05500
8     Neptune           30.0  17.00000
9       Pluto           39.0   0.00218
6      Saturn            9.5  95.00000

  Planet name  Distance (AU)     Mass
5     Jupiter            5.2  318.000
3        Mars            1.5    0.107
0     Mercury            0.4    0.055

-------
Empty DataFrame
Columns: [Planet name, Distance (AU), Mass]
Index: []

  Planet name  Distance (AU)   Mass
2       Earth            1.0    1.0
5     Jupiter            5.2  318.0