PythonPandas.com

How to Access Columns by index in Pandas



In Pandas, accessing columns by their index is useful when you want to retrieve specific columns based on their position, rather than their name. This can be done using various methods, such as iloc[], iat[], or using columns to get the column name by position. In this article, we’ll explore these methods with examples.

Pandas: How to Access or Select Columns by Index, not by Name

Method 1: Access Column by Index Using iloc[]

iloc[] is used to access columns by their integer position (index). This method is very useful when you need to access columns in a specific order, regardless of the column names.

Example: Access Column by Index Using iloc[]

import pandas as pd

# Sample DataFrame
data = {'Name': ['John', 'Alice', 'Bob'],
        'Age': [25, 30, 22],
        'Gender': ['Male', 'Female', 'Male']}
df = pd.DataFrame(data)
# Access the column at index position 1 (second column, 'Age')
column = df.iloc[:, 1]
print(column)

Output:

0    25
1    30
2    22
Name: Age, dtype: int64

In this example, we use iloc[] to access the column at position 1 (the second column). The result is the ‘Age’ column.

How to Access Columns by index in Pandas — PythonPandas.com
pythonpandas.com

Method 2: Access Column by Index Using iat[]

iat[] is similar to iloc[], but it is used for accessing a single element at a specific row and column index. It’s very efficient for accessing individual values in the DataFrame.

Example: Access Column by Index Using iat[]

# Access the first element in the second column (Age)
value = df.iat[0, 1]
print(value)

Output:

25

In this example, we use iat[] to access the value at row 0, column 1 (the first element of the ‘Age’ column).

Method 3: Access Column by Index Using columns

Another way to access a column by its index is by using the columns attribute, which stores the column labels. You can use the column index to get the column name and then access the column using loc[] or iloc[].

Example: Access Column by Index Using columns

# Get the column name at index position 1
column_name = df.columns[1]
# Access the column using loc[]
column = df[column_name]
print(column)

Output:

0    25
1    30
2    22
Name: Age, dtype: int64

In this example, we first use df.columns[1] to retrieve the column name at position 1 (which is ‘Age’), and then we access that column using df[column_name].

Method 4: Access Multiple Columns by Index Using iloc[]

You can also use iloc[] to select multiple columns by their index positions.

Example: Access Multiple Columns by Index Using iloc[]

# Access columns at index positions 0 and 2
columns = df.iloc[:, [0, 2]]
print(columns)

Output:

Name  Gender
0   John    Male
1  Alice  Female
2    Bob    Male

In this example, we use iloc[] to select multiple columns at positions 0 and 2 (‘Name’ and ‘Gender’).

Summary

Accessing columns by index in Pandas can be done using iloc[], iat[], or by using the columns attribute to retrieve the column names. iloc[] is useful for accessing columns by integer positions, while iat[] is used for retrieving specific values from a column at a specific index. By combining these methods, you can efficiently access and manipulate columns in a DataFrame based on their positions.

Frequently Asked Questions — How to Access Columns by Index in Pandas

How do I access a column by index in Pandas?

Use the iloc indexer to access columns by their numerical position:

import pandas as pd
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6],'C':[7,8,9]})
print(df.iloc[:, 1])  # Access second column (index 1)

This returns the column at position 1.

How do I access multiple columns by index?

You can pass a list or range of indexes to iloc:

# Access first and third columns
df.iloc[:, [0, 2]]

# Access columns from index 0 to 1
df.iloc[:, 0:2]

How can I get the column name using an index number?

Use df.columns with an index to fetch the column label:

col_name = df.columns[1]
print(col_name)  # 'B'

How do I access the last column by index?

Use negative indexing with iloc:

df.iloc[:, -1]  # Access the last column

Can I rename a column accessed by index?

Yes, use rename() with df.columns[index]:

df.rename(columns={df.columns[1]: 'NewName'}, inplace=True)

This changes the name of the column at position 1.

How to loop through all columns using index numbers?

You can iterate over range(len(df.columns)):

for i in range(len(df.columns)):
    print(df.columns[i], df.iloc[:, i].head())

How do I access a column by index inside iterrows()?

Inside iterrows(), use df.columns[i] to access by index:

for i, row in df.iterrows():
    print(row[df.columns[1]])  # Access column by index

What’s the difference between iloc and loc when accessing columns?
  • iloc → integer-based (index position)
  • loc → label-based (column name)
df.iloc[:, 0]   # first column
df.loc[:, 'A']  # column named 'A'

How can I select every nth column using index?

Use slicing with a step value:

# Access every 2nd column
df.iloc[:, ::2]

How do I access columns by index in a DataFrame with multi-level columns?

Use tuple-style indexing or iloc depending on your level:

# For MultiIndex columns
df.iloc[:, 0]  # still works by position
# or access by level
df['Level1']['SubCol']

Related Post