Multiply Columns To Make New Column Pandas

Community request time! Thanks to Leonah for the tutorial request about how to multiply columns in pandas

Multiplying columns together is a foundational skill in Pandas and a great one to master. Good thing it is straightforward and easy to pick up.

1. df['your_new_column'] = df['col1'] * df['col2']

In the video below we’ll review two methods for multiplying columns together and saving the result on your dataframe.

Code from the video. Looks like the formatting of many columns is very off. To view a nice version, head over to the git hub link below.


Mulitplying columns together to make a 3rd column

Goal: Multiply columns

In [1]:
import pandas as pd
In [2]:
df = pd.read_csv('../data/Street_Tree_List.csv')
In [4]:
df.head(2)
Out[4]:
TreeIDqLegalStatusqSpeciesqAddressSiteOrderqSiteInfoPlantTypeqCaretakerqCareAssistantPlantDate...XCoordYCoordLatitudeLongitudeLocationFire Prevention DistrictsPolice DistrictsSupervisor DistrictsZip CodesNeighborhoods (old)
046534Permitted SiteTree(s) ::73 Summer St7.0Sidewalk: Curb side : CutoutTreePrivateNaN04/01/2002 12:00:00 AM...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
1121399DPW MaintainedCorymbia ficifolia :: Red Flowering Gum349X Cargo Way1.0Sidewalk: Curb side : CutoutTreeDPWNaNNaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN

2 rows × 23 columns

Method 1: Multiply Series together

In [9]:
df['multiplied_column'] = df['TreeID'] * df['SiteOrder']

Method 2: Iterate through column and multiply

In [20]:
results_list = []

for i, row in df.iterrows():
    result = (row['TreeID']/2) * row['SiteOrder']
    results_list.append(result)
In [22]:
df['multiplied_column2'] = results_list
In [23]:
df.head(3)
Out[23]:
TreeIDqLegalStatusqSpeciesqAddressSiteOrderqSiteInfoPlantTypeqCaretakerqCareAssistantPlantDate...LatitudeLongitudeLocationFire Prevention DistrictsPolice DistrictsSupervisor DistrictsZip CodesNeighborhoods (old)multiplied_columnmultiplied_column2
046534Permitted SiteTree(s) ::73 Summer St7.0Sidewalk: Curb side : CutoutTreePrivateNaN04/01/2002 12:00:00 AM...NaNNaNNaNNaNNaNNaNNaNNaN325738.0162869.0
1121399DPW MaintainedCorymbia ficifolia :: Red Flowering Gum349X Cargo Way1.0Sidewalk: Curb side : CutoutTreeDPWNaNNaN...NaNNaNNaNNaNNaNNaNNaNNaN121399.060699.5
285269Permitted SiteArbutus 'Marina' :: Hybrid Strawberry Tree1000 Edinburgh St3.0Sidewalk: Curb side : CutoutTreePrivateNaN07/24/2007 12:00:00 AM...NaNNaNNaNNaNNaNNaNNaNNaN255807.0127903.5

3 rows × 25 columns

In [ ]:
 

Link to code above

Check out more Pandas functions on our Pandas Page