How to select a list of rows by name in Pandas dataframe
You can use df.loc[['TP3','TP12','TP18']]
Here is a small example:
In [26]: df = pd.DataFrame({"a": [1,2,3], "b": [3,4,5], "c": [5,6,7]})In [27]: df.index = ["x", "y", "z"]In [28]: dfOut[28]: a b cx 1 3 5y 2 4 6z 3 5 7[3 rows x 3 columns]In [29]: df.loc[["x", "y"]]Out[29]: a b cx 1 3 5y 2 4 6[2 rows x 3 columns]
There are at least 3 ways to access the element of of a pandas dataframe.
import pandas as pdimport numpy as npdf=pd.DataFrame(np.random.uniform(size=(10,10)),columns= list('PQRSTUVWXY'),index= list("ABCDEFGHIJ"))
Using df[['P','Q']]
you can only access the columns of the dataframe. You can use the dataframe.loc[]
(stands for location) or dataframe.iloc[]
(stands for index location) numpy style slicing of the dataframe.
df.loc[:,['P','Q']]
Above will give you columns named by 'P' and 'Q'.
df.loc[['A','B'],:]
Above will return rows with keys 'A' and 'B'.
You can also use number based slicing using iloc
method.
df.iloc[:,[1,2]]
This will return columns numbered by 1 and 2.While,
df.iloc[[1,2],:]
will return rows 1st and 2nd.You can access any specific element by
df.iloc[1,2]
or,
df.loc['A','Q']