To use a variable as a column name in pandas, you can follow these steps:
First, import the pandas library:
import pandas as pd
Next, create a DataFrame with some sample data:
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]} df = pd.DataFrame(data)
Now, let’s say you have a variable called column_name
and you want to access the column in the DataFrame with that name:
column_name = 'B'
To access the column with the specified name, you can use square brackets notation:
df[column_name]
This will return the column with the name ‘B’ from the DataFrame:
0 4 1 5 2 6 Name: B, dtype: int64
You can also assign the column to a new variable if needed:
new_variable = df[column_name]
Now new_variable
will contain the column with the name ‘B’ from the DataFrame.