Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - How to select a column from a Pandas DataFrame
To select a column from a Pandas DataFrame, use square brackets with the column name. This returns a Series object containing all values from that column.
Syntax
dataFrame['ColumnName']
Basic Column Selection
First, let's create a DataFrame and select a single column ?
import pandas as pd
# Create DataFrame
dataFrame = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
print("DataFrame ...")
print(dataFrame)
DataFrame ...
Car Units
0 BMW 100
1 Lexus 150
2 Audi 110
3 Mustang 80
4 Bentley 110
5 Jaguar 90
Selecting a Single Column
Use square brackets to select the 'Car' column ?
import pandas as pd
# Create DataFrame
dataFrame = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
# Selecting a column
selected_column = dataFrame['Car']
print("Selecting and displaying only a single column:")
print(selected_column)
Selecting and displaying only a single column: 0 BMW 1 Lexus 2 Audi 3 Mustang 4 Bentley 5 Jaguar Name: Car, dtype: object
Alternative Methods
You can also use dot notation for column selection ?
import pandas as pd
dataFrame = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi'],
"Units": [100, 150, 110]
}
)
# Using dot notation
car_series = dataFrame.Car
print("Using dot notation:")
print(car_series)
Using dot notation: 0 BMW 1 Lexus 2 Audi Name: Car, dtype: object
Key Points
- Square bracket notation works for all column names
- Dot notation only works if column names are valid Python identifiers
- Both methods return a Pandas Series object
- Column selection preserves the original index
Conclusion
Use square brackets dataFrame['ColumnName'] to select columns from a DataFrame. This returns a Series with the column data and original index preserved.
Advertisements
