4.16. DataFrame Slicing

import numpy as np
import pandas as pd

np.random.seed(0)


values = np.random.randn(6, 4)
columns = ['Morning', 'Noon', 'Evening', 'Midnight']
indexes = pd.date_range('1970-01-01', periods=6)

df = pd.DataFrame(values, index=indexes, columns=columns)
#               Morning       Noon    Evening   Midnight
# 1970-01-01   0.486726  -0.291364  -1.105248  -0.333574
# 1970-01-02   0.301838  -0.603001   0.069894   0.309209
# 1970-01-03  -0.424429   0.845898  -1.460294   0.109749
# 1970-01-04   0.909958  -0.986246   0.122176   1.205697
# 1970-01-05  -0.172540  -0.974159  -0.848519   1.691875
# 1970-01-06   0.047059   0.359687   0.531386  -0.587663

4.16.1. Slicing by index

4.16.1.1. Single row

df[1]
# 1970-01-02   0.301838  -0.603001   0.069894   0.309209

4.16.1.2. Rows range

df[1:3]
# 1970-01-02   0.301838  -0.603001   0.069894   0.309209
# 1970-01-03  -0.424429   0.845898  -1.460294   0.109749

4.16.2. Slicing by columns

4.16.2.1. Single column

df.Morning
# 1970-01-01   -0.438232
# 1970-01-02   -1.798254
# 1970-01-03   -0.802938
# 1970-01-04    0.820863
# 1970-01-05    1.800466
# 1970-01-06    0.141029
# Freq: D, Name: Morning, dtype: float64
df['Morning']
# 1970-01-01   -0.438232
# 1970-01-02   -1.798254
# 1970-01-03   -0.802938
# 1970-01-04    0.820863
# 1970-01-05    1.800466
# 1970-01-06    0.141029
# Freq: D, Name: Morning, dtype: float64

4.16.2.2. Multiple columns

df[['Morning', 'Evening']]
#               Morning    Evening
# 1970-01-01  -0.438232  -1.113116
# 1970-01-02  -1.798254  -0.946041
# 1970-01-03  -0.802938  -0.258279
# 1970-01-04   0.820863  -0.901532
# 1970-01-05   1.800466   0.611194
# 1970-01-06   0.141029  -0.046938

4.16.2.3. Column range

df.loc[:, 'Morning':'Evening']
#                     Morning            Noon         Evening
# 1970-01-01        -1.185919        0.929399        0.546952
# 1970-01-02         1.223428       -0.132430       -0.504896
# 1970-01-03         0.377136       -0.637106       -0.104753
# 1970-01-04         0.844626        0.908642        0.982422
# 1970-01-05         0.089944       -0.706245        0.052225
# 1970-01-06         1.382942        0.386913       -1.332453

4.16.3. Assignments

Todo

Create assignments