0
0
Data Analysis Pythondata~5 mins

Selecting columns in Data Analysis Python

Choose your learning style9 modes available
Introduction

We select columns to focus on specific parts of data we want to analyze or use.

You want to see only the names and ages from a list of people.
You need to analyze sales numbers without other details.
You want to create a new table with just a few important columns.
You want to remove extra information before sharing data.
You want to plot data using only certain columns.
Syntax
Data Analysis Python
df['column_name']
df[['col1', 'col2']]
df.column_name

Use single brackets and a string to select one column.

Use double brackets and a list of strings to select multiple columns.

Examples
Selects the column named 'Age' from the DataFrame.
Data Analysis Python
df['Age']
Selects two columns 'Name' and 'Age' as a new DataFrame.
Data Analysis Python
df[['Name', 'Age']]
Another way to select the 'Name' column using dot notation.
Data Analysis Python
df.Name
Sample Program

This code creates a table with names, ages, and cities. Then it shows how to pick just the 'Age' column and also how to pick 'Name' and 'City' columns together.

Data Analysis Python
import pandas as pd

# Create a simple DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['NY', 'LA', 'Chicago']}
df = pd.DataFrame(data)

# Select the 'Age' column
ages = df['Age']
print('Ages column:')
print(ages)

# Select 'Name' and 'City' columns
name_city = df[['Name', 'City']]
print('\nName and City columns:')
print(name_city)
OutputSuccess
Important Notes

Using single brackets returns a Series (one column).

Using double brackets returns a DataFrame (multiple columns).

Dot notation works only if the column name has no spaces or special characters.

Summary

Select columns to focus on data you need.

Use df['col'] for one column, df[['col1', 'col2']] for many.

Dot notation is a shortcut but has limits.