5.17. DataFrame Slicing

import numpy as np
import pandas as pd

np.random.seed(0)


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

df = pd.DataFrame(data, index, 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

5.17.1. Rows

5.17.1.1. Slicing by index

import numpy as np
import pandas as pd

np.random.seed(0)


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

df = pd.DataFrame(data, index, 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

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

5.17.2. Columns

5.17.2.1. Column range

import numpy as np
import pandas as pd

np.random.seed(0)


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

df = pd.DataFrame(data, index, 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

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

5.17.3. Assignments

Todo

Create assignments