How to get column and row names in DataFrame?

How to get column and row names in DataFrame?

In pandas, if you have a DataFrame, you can easily retrieve its column and row names (labels) using attributes of the DataFrame.

Here's how you can get the column and row names:

  1. Column Names:

    Use the .columns attribute of the DataFrame to get the column names.

    import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9] }) # Get column names column_names = df.columns print(column_names) 

    Output:

    Index(['A', 'B', 'C'], dtype='object') 

    If you want the column names as a list, you can convert the above result using tolist():

    column_names_list = df.columns.tolist() print(column_names_list) 

    Output:

    ['A', 'B', 'C'] 
  2. Row Names (Index):

    Use the .index attribute of the DataFrame to get the row names or labels.

    # Get row names/index row_names = df.index print(row_names) 

    Output (for the above sample DataFrame):

    RangeIndex(start=0, stop=3, step=1) 

    Again, if you want the row names as a list, you can convert the result:

    row_names_list = df.index.tolist() print(row_names_list) 

    Output:

    [0, 1, 2] 

Keep in mind that the row names in pandas are usually referred to as the "index" of the DataFrame.


More Tags

motion-detection android-color page-factory bamboo offset bootbox drawrectangle nsnotificationcenter jobs roguelike

More Programming Guides

Other Guides

More Programming Examples