pandas: multiply column by column from another dataframe?

  • Last Update :
  • Techknowledgy :

Here you go. I have created a variable that allows you to select that which column of the second dataframe you want to multiply with the numbers in the first dataframe.

arr1 = np.array(df1) # df1 to array

which_df2col_to_multiply = 0 # select col from df2
arr2 = np.array(df2)[: , which_df2col_to_multiply] # selected col to array

print(np.transpose(arr2 * arr1)) # result

This is the output:

[
   [1 2 3]
   [4 4 4]
   [12 8 4]
]

Assuming your column names are 0,1,2

df1.mul(df2[1], 0)

Output

    0 1 2
    0 1 2 3
    1 4 4 4
    2 12 8 4

Suggestion : 2

Get Multiplication of dataframe and other, element-wise (binary operator mul).,Equivalent to dataframe * other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, rmul.,Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.,Multiply a DataFrame of different shape with operator version.

>>> df = pd.DataFrame({
         'angles': [0, 3, 4],
         ...'degrees': [360, 180, 360]
      },
      ...index = ['circle', 'triangle', 'rectangle']) >>>
   df
angles degrees
circle 0 360
triangle 3 180
rectangle 4 360
>>> df + 1
angles degrees
circle 1 361
triangle 4 181
rectangle 5 361
>>> df.add(1)
angles degrees
circle 1 361
triangle 4 181
rectangle 5 361
>>> df.div(10)
angles degrees
circle 0.0 36.0
triangle 0.3 18.0
rectangle 0.4 36.0
>>> df.rdiv(10)
angles degrees
circle inf 0.027778
triangle 3.333333 0.055556
rectangle 2.500000 0.027778
>>> df - [1, 2]
angles degrees
circle - 1 358
triangle 2 178
rectangle 3 358

Suggestion : 3

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.,In the video below we’ll review two methods for multiplying columns together and saving the result on your dataframe.,Community request time! Thanks to Leonah for the tutorial request about how to multiply columns in pandas,Want to get our Top 10 Pandas functions? Get them delivered to your inbox

1. df['your_new_column'] = df['col1'] * df['col2']
import pandas as pd
df = pd.read_csv('../data/Street_Tree_List.csv')
df.head(2)
df['multiplied_column'] = df['TreeID'] * df['SiteOrder']
results_list = []

for i, row in df.iterrows():
   result = (row['TreeID'] / 2) * row['SiteOrder']
results_list.append(result)

Suggestion : 4

In this example, we’ll create a new DataFrame column by multiplying the values of two additional columns. Here’s the code:,In Data Analysis we often need to execute arithmetic operations on our dataset. In today’s tutorial we would like to show how you can easily multiply two or more columns in a single DataFrame or on multiple ones.,If you have your data in different DataFrames you can obviously concatenate or join then together. You can also create new columns in your Python DataFrame by performing arithmetic operations between matching rows element wise.,We will start by defining two DataFrames to run through the tutorials examples using the pd.DataFrame() constructor.

We will start by defining two DataFrames to run through the tutorials examples using the pd.DataFrame() constructor.

import pandas as pd

#define DataFrames
df1 = pd.DataFrame({
   'employee': ['Larry', 'Liam', 'Niall'],
   'hours_worked': [90, 80, 80],
   'salary_hour': [24.3, 31.5, 45.4]
})

df2 = pd.DataFrame({
   'employee': ['Larry', 'Liam', 'Niall'],
   'hourly_sold_units': [120, 90, 100]
})

In this example, we’ll create a new DataFrame column by multiplying the values of two additional columns. Here’s the code:

df1['total_salary'] = df1['hours_worked'] * df1['salary_hour']

df1.head()

In this example we would like to calculate the salary only for employees who worked over 80 hours.

df1['overtime_salary'] = (df1['hours_worked'] > 80) * df1['hours_worked'] * df1['salary_hour']

print(df1.head())

We can easily now go ahead and sum the values of the new calculated column:

print(df1['total_sales'].sum())

If we just want to multiply column values by a constant value:

df1['net_sales'] = df1['total_sales'] * 0.77

Suggestion : 5

Update multiple columns from another dataframe based on one common column in Pandas,If you join the dfs first then you can then multiply:,Running an operation on one column based on content from another column in Pandas Dataframe,How to calculate the values of a pandas DataFrame column depending on the results of a rolling function from another column

If you join the dfs first then you can then multiply:

In[24]:
   df3 = df1.join(df2)
df3['percent'] = df3['num_percent'] * df3['total_quantity']
df3

Out[24]:
   num_percent org total_quantity percent
month
2014 - 01 - 01 0.4 00 K 1000 400
2014 - 01 - 01 0.4 00 L 1000 400
2014 - 02 - 01 0.5 00 K 1000 500
2014 - 03 - 01 0.6 00 K 2000 1200

Suggestion : 6

3 days ago DataFrame.multiply(other, axis='columns', level=None, fill_value=None) [source] ¶. Get Multiplication of dataframe and other, element-wise (binary operator mul ). Equivalent to dataframe * other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, rmul. , 1 day ago In this tutorial, we will discuss and learn the Python pandas DataFrame.multiply() method. This method is used to get the multiplication of the dataframe and other, element-wise. It returns a DataFrame with the result of the multiplication operation. The syntax is shown below. Syntax DataFrame.multiply(other, axis='columns', level=None, fill_value=None) ,How To Multiply Every Column Of One Pandas Dataframe With Every Column Of Anothe,I'm trying to multiply two pandas dataframes with each other. Specifically, I want to multiply every column with every column of the other df.


col_1, col_2, col_3, ...0 1 0 1 0 0 0 0 1...

# use numpy to get a pair of indices that map out every # combination of columns from df_1 and columns of df_2 pidx = np.indices((df_1.shape[1], df_2.shape[1])).reshape(2, -1) # use pandas MultiIndex to create a nice MultiIndex
for # the final output lcol = pd.MultiIndex.from_product([df_1.columns, df_2.columns], names = [df_1.columns.name, df_2.columns.name]) # df_1.values[: , pidx[0]] slices df_1 values
for every combination # like wise with df_2.values[: , pidx[1]] #
finally, I marry up the product of arrays with the MultiIndex pd.DataFrame(df_1.values[: , pidx[0]] * df_2.values[: , pidx[1]], columns = lcol)
col_1, col_2, col_3, ...010 100 001...
interact_pd = pd.DataFrame(index = df_1.index) df1_columns = [column
   for column in df_1
]
for column in df_2: col_pd = df_1[df1_columns].multiply(df_2[column], axis = "index") interact_pd = interact_pd.join(col_pd, lsuffix = '_' + column)
1 col_1, 1 col_2, 1 col_3 010 100 001
2 col_1, 2 col_2 01 10 00