How to Select single column of a Pandas Dataframe?

How to Select single column of a Pandas Dataframe?

To select a single column of a pandas DataFrame, you can use either the "dot notation" or the "bracket notation".

Here's how you can do it:

  1. Using Dot Notation:

    You can access a column using the dot notation if the column name does not contain spaces and is not named after any DataFrame method or attribute:

    import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6] }) # Select column A column_a = df.A 

    Note: While this method is convenient, it doesn't work for column names that contain spaces or have the same name as DataFrame methods.

  2. Using Bracket Notation:

    The bracket notation works for any column name:

    column_a = df['A'] 

    This is the most versatile method and is generally preferred for most use cases.

Once you've selected a column using either of these methods, the resulting object is a pandas Series. If you want to keep it as a DataFrame, you can use double brackets:

column_a_df = df[['A']] 

This will return a DataFrame with only the 'A' column, rather than a Series.


More Tags

csrf firefox flask-restful fileinputstream voip slack log4j aws-java-sdk opensuse app-store

More Programming Guides

Other Guides

More Programming Examples