Home > Blockchain >  Column wise multiplication of a set of Dataframe with elements of other Dataframe
Column wise multiplication of a set of Dataframe with elements of other Dataframe

Time:11-22

I have few pandas DataFrames (say a, b, c) like this: enter image description here enter image description here enter image description here

And another Dataframe (name it x), whose number of rows are equal to the number of dataframes like above:

enter image description here


How can I multiply the entire first column of the first dataframe (a) with x[0][0]?
Then the second column of the dataframe a (bb_11) with x[0][1].
Then the third column of the dataframe a (cc_12) with x[0][2], and so on.

For dataframe b, we should use the second row of x, i.e. x[1][j] (where j varies from 0-3). That is, I need to multiply the entire first column of the second dataframe (b) with x[1][0].
Then the second column of the dataframe b (bb_11) with x[1][1].
Then the third column of the dataframe b (cc_12) with x[1][2], and so on.

N.B. All dataframe column names will be the same. Our dataframes will be read from a file so looping will be an easier option.


Sample Data:

import pandas as pd
  
d = {'aa_10' : pd.Series([np.nan, 2, 3, 4]),
     'bb_11' : pd.Series([6, np.nan, 8, 9]),
     'cc_12' : pd.Series([1, 2, np.nan, 4]),
     'dd_13' : pd.Series([6, 7, 8, np.nan])}
  
# creates Dataframe.
a = pd.DataFrame(d)
  
# print the data.
print (a)

# Initialize data to Dicts of series.
d = {'aa_10' : pd.Series([np.nan, 12, 13, 14]),
     'bb_11' : pd.Series([16, np.nan, 18, 19]),
     'cc_12' : pd.Series([11, 12, np.nan, 14]),
     'dd_13' : pd.Series([16, 17, 18, np.nan])}
  
# creates Dataframe.
b = pd.DataFrame(d)
  
# print the data.
print(b)

# Initialize data to Dicts of series.
d = {'aa_10' : pd.Series([np.nan, 21, 31, 41]),
     'bb_11' : pd.Series([61, np.nan, 81, 91]),
     'cc_12' : pd.Series([11, 21, np.nan, 41]),
     'dd_13' : pd.Series([61, 71, 81, np.nan])}
  
# creates Dataframe.
c = pd.DataFrame(d)
  
# print the data.
print(c)

# Initialize data to Dicts of series.
d = {'aa_10' : pd.Series([1, 2, 3]),
     'bb_11' : pd.Series([6, 7, 8]),
     'cc_12' : pd.Series([10, 11, 12]),
     'dd_13' : pd.Series([13, 14, 15])}
  
# creates Dataframe.
x = pd.DataFrame(d)
  
# print the data.
print(x)

CodePudding user response:

You can do that

a,b,c = [x.mul(y) for x , y in zip([a,b,c],x.values.tolist())]
a
   aa_10  bb_11  cc_12  dd_13
0    NaN   36.0   10.0   78.0
1    2.0    NaN   20.0   91.0
2    3.0   48.0    NaN  104.0
3    4.0   54.0   40.0    NaN
  • Related