Examples of how to get the names (titles or labels) of a pandas data frame in python
Get the row names of a pandas data frame
Let's consider a data frame called df. to get the row names a solution is to do:
>>> df.index
Get the row names of a pandas data frame (Exemple 1)
Let's create a simple data frame:
>>> import pandas as pd>>> import numpy as np>>> data = np.arange(1,13)>>> data = data.reshape(3,4)>>> dataarray([[ 1, 2, 3, 4],[ 5, 6, 7, 8],[ 9, 10, 11, 12]])>>> columns = ['Home','Car','Sport','Food']>>> index = ['Alice','Bob','Emma']>>> df = pd.DataFrame(data=data,index=index,columns=columns)>>> dfHome Car Sport FoodAlice 1 2 3 4Bob 5 6 7 8Emma 9 10 11 12
To get the names of the data frame rows:
>>> df.indexIndex(['Alice', 'Bob', 'Emma'], dtype='object')
Get the row names of a pandas data frame (Exemple 2)
Another example using the csv file train.csv (that can be downloaded on kaggle):
>>> import pandas as pd>>> df = pd.read_csv('train.csv')>>> df.indexRangeIndex(start=0, stop=1460, step=1)
Select rows of a pandas data frame
Example 1:
>>> import pandas as pd>>> import numpy as np>>> data = np.arange(1,13)>>> data = data.reshape(3,4)>>> columns = ['Home','Car','Sport','Food']>>> index = ['Alice','Bob','Emma']>>> df = pd.DataFrame(data=data,index=index,columns=columns)>>> dfHome Car Sport FoodAlice 1 2 3 4Bob 5 6 7 8Emma 9 10 11 12>>> df.loc['Bob',:]Home 5Car 6Sport 7Food 8Name: Bob, dtype: int64>>> df.loc['Bob',['Car','Food']]Car 6Food 8Name: Bob, dtype: int64
Example 2:
>>> import pandas as pd>>> df = pd.read_csv('train.csv')>>> df.loc[0,:]Id 1MSSubClass 60MSZoning RLLotFrontage 65LotArea 8450Street PaveAlley NaNLotShape RegLandContour LvlUtilities AllPubLotConfig InsideLandSlope GtlNeighborhood CollgCrCondition1 NormCondition2 NormBldgType 1FamHouseStyle 2StoryOverallQual 7OverallCond 5YearBuilt 2003YearRemodAdd 2003RoofStyle GableRoofMatl CompShgExterior1st VinylSdExterior2nd VinylSdMasVnrType BrkFaceMasVnrArea 196ExterQual GdExterCond TAFoundation PConc...BedroomAbvGr 3KitchenAbvGr 1KitchenQual GdTotRmsAbvGrd 8Functional TypFireplaces 0FireplaceQu NaNGarageType AttchdGarageYrBlt 2003GarageFinish RFnGarageCars 2GarageArea 548GarageQual TAGarageCond TAPavedDrive YWoodDeckSF 0OpenPorchSF 61EnclosedPorch 03SsnPorch 0ScreenPorch 0PoolArea 0PoolQC NaNFence NaNMiscFeature NaNMiscVal 0MoSold 2YrSold 2008SaleType WDSaleCondition NormalSalePrice 208500Name: 0, dtype: object
References
| Links | Site |
|---|---|
| Index | pandas doc |
| Select Rows & Columns by Name or Index in DataFrame using loc & iloc Python Pandas | thispointer.com |
| Different ways to create Pandas Dataframe | geeksforgeeks |
| pandas.DataFrame | pandas.pydata.org |
| read_csv | pandas.pydata.org |
