Exemple de comment obtenir les noms (titres, labels) associés aux lignes d'un tableau de données (data frame) avec pandas sous python:
Obtenir le noms associés aux lignes d'une data frame
Soit une data frame nommée df, pour obtenir le noms associés aux lignes on peut faire comme ceci:
>>> df.index
Obtenir le noms associés aux lignes d'une data frame (Exemple 1)
Créons une 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
On peut alors retrouver le noms associés aux lignes comme ceci:
>>> df.indexIndex(['Alice', 'Bob', 'Emma'], dtype='object')
Obtenir le noms associés aux lignes d'une data frame (Exemple 2)
Autre exemple avec le fichier csv suivant train.csv (que l'on peut télécharger sur kaggle):
>>> import pandas as pd>>> df = pd.read_csv('train.csv')>>> df.indexRangeIndex(start=0, stop=1460, step=1)
ici il n'existe pas de noms associés aux lignes du tableau
Sélectionner une ligne d'une data frame
Exemple 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
Exemple 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
Références
| Liens | 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 |
