Skip to content

Pandas DataFrame Columns Fix

DodaTech Updated 2026-06-26 1 min read

You will learn how to select, rename, and manipulate columns in DataFrames.

The Wrong Way

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4], 'C': [5, 6]})
print(df['A'])

Output:

0    1
1    2
Name: A, dtype: int64

The Right Way

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4], 'C': [5, 6]})
print(df[['A', 'C']])

Output:

   A  C
0  1  5
1  2  6

Step-by-Step Fix

1. Understand the data structure

Check the shape, index, and dtypes before performing operations. Use .info() and .describe() to inspect.

print(df.info())
print(df.describe())
print(df.head())

2. Perform the operation

Apply the corrected method with proper parameters as shown above.

3. Verify the result

Always verify the output matches expectations:

print(result.shape)
print(result.head())
print(result.dtypes)

Prevention Tips

  • Use df['col'] for a single column (returns Series)
  • Use df[['col1', 'col2']] for multiple columns (returns DataFrame)
  • Use df.rename(columns={'old':'new'}) for renaming
  • Use df.columns.tolist() to see column names
  • Use df.columns = ['new1', 'new2'] to replace all names

Common Mistakes

  1. Using single brackets for multiple columns (returns Series)
  2. Assigning column list without matching length
  3. Confusing df.col (attribute access) with df['col'] (bracket access)

These mistakes appear frequently in real-world pandas code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Given a DataFrame with columns ['first_name', 'last_name', 'age', 'salary'], select name columns only, rename them.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between df['col'] and df.col?

df.col only works for valid Python identifiers and can conflict with DataFrame methods.

How do I select columns by data type?

Use df.select_dtypes(include=['int64', 'float64']).

Can I reorder columns?

Yes: df = df[['c', 'a', 'b']] reorders to c, a, b.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro