Ready to write Python code 4x faster?
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.
More Like This
Automating Spreadsheets with Python 101
How to tell the difference between a good and bad Python automation target.
10 Mistakes To Look Out For When Transitioning from Excel To Python
10 Common Mistakes for new programmers transitioning from Excel to Python
Research shows Mito speeds up by 400%
We're always on the hunt for tools that improve our efficiency at work. Tools that let us accomplish more with less time, money, and resources.
3 Rules for Choosing Between SQL and Python
Analysts at the world's top banks are automating their manual Excel work so they can spend less time creating baseline reports, and more time building new analyses that push the company forward.