Add a Column to a Pandas Dataframe
Adding a column to a pandas dataframe allows you to create new and useful calculations from existing data in your dataframe.
The code you probably want
Adding a new column to the end of the dataframe and setting it equal to a transformation of existing columns.
import pandas as pd
df = pd.DataFrame({'amount': [3, 2], 'price': [2.1, 2.3]})
df['revenue'] = df['amount'] * df['price']
Other Common Use Cases
Insert new column at a specific index
import pandas as pd
df = pd.DataFrame({'amount': [3, 2], 'price': [2.1, 2.3]})
df.insert(0, 'revenue', df['amount'] * df['price'])
Insert new column that replaces pieces of strings in a different column
import pandas as pd
df = pd.DataFrame({'id': ['id-1', 'id-2'], 'amount': [5, 3]})
df['id_number'] = df['id'].str.replace('-', '_')
Insert new column that uses an IF statement
import pandas as pd
df = pd.DataFrame({'amount': [200, 50]})
df['sold more than 100'] = df['amount'].apply(lambda amt: 'Yes' if amt > 100 else 'No')
You can find a full collection of Pandas IF statement examples here.
Insert new column that parses out part of an existing string column
import pandas as pd
df = pd.DataFrame({'id': ['id-1', 'id-2'], 'amount': [5, 3]})
df['id_number'] = df['id'].str.split("-").str[-1]
What is this blog post
At Mito, we’ve spent years working with users to automate their data work in Python. As such, we’ve got a great sense of what the most common use cases are for common pandas functions.
This blog post is the first in a series of tutorials - designed to be the best pandas documentation for you most of the time. There’s no BS marketing langauge at the top of this blog post, and we rank (easy to copy!) code snippets depending on how likely you are to be encountering them.
If you’re looking to save time writing Python code, we recommend checking out Mito - we built it with the same set of learnings that helped us build the best pandas tutorials ever!
With Mito, you can add new columns and write formulas just like you would in Excel or Google sheets - and we write the Python code for you. See our documentation here.