How to access a DataFrame column with Pandas
• 1 minWhen you will use Pandas DataFrame you certainly will need to access its columns.
Here two ways to access it :
- Using squared brackets
- Using dot
Generating the example DataFrame
# We create our dataframe example
df = pd.DataFrame({"col1":range(0,10)})
# We print it
print(df)
Using squared brackets
print(df["col1"])
df["col2"] = df["col1"] + 1
Using dot
print(df.col1)
Be careful with this method since it is not possible to have column names with spaces or weird characters and creating a new column is not possible like this.
df.col3 = df.col1 + 1 # This won't work
print(df.My Amzing Column) # This won't work
Here you are ! You are now an expert at accessing DataFrame columns !
More on DataFrames
If you want to know more about DataFrame and Pandas. Checkout the other articles I wrote on the topic, just here :
Pandas - The Python You Need
We gathered the only Python essentials that you will probably ever need.