Reputation: 6615
I have pandas data frames which share at least some common column names. The position of the column names is not guaranteed to be the same, but I want to multiply them together if they share a common name.
For example, in data frame "A" income may be the 3rd column but in data frame "B" income could be the 11th column. Is there a way I can multiply these together using common column names?
df1=pd.DataFrame({'a':[1,3,5],'c':[10,20,40],'b':[8,6,4]})
df2=pd.DataFrame({'b':[1,33,5],'a':[10,200,7],'c':[0,6,1]})
I'd like to multiply these together. Positions of each columns are never guaranteed to be in the same spot. Any 'smart' ways? To do this.
I had put together code where I would look for the intersection of column names and then sort them alphabetically and then multiply, but I'm figuring there is something a bit more intelligent?
Sorry if this is too obvious of a question, I just figure there has to be something smart out there in pandas that doesn't require me writing 20 lines of code.
Upvotes: 1
Views: 635
Reputation: 5183
You can do something like
df3 =pd.DataFrame()
for colname in df1.columns:
df3[colname] = df1[colname] * df2[colname]
This is useful of there are more columns in df1 and df2
Upvotes: 0
Reputation: 15568
You can just multiply them. As long as they have the same columns name and rows number
import pandas as pd
df1=pd.DataFrame({'a':[1,3,5],'c':[10,20,40],'b':[8,6,4]})
df2=pd.DataFrame({'b':[1,33,5],'a':[10,200,7],'c':[0,6,1]})
df = df1 * d2
print(df)
Results
Upvotes: 1
Reputation: 36
I think this isn't the most efficient way to do this, but is something that would work:
name = "income"
for col1 in df1.columns:
for col2 in df2.columns:
if (col1 == name) and (col2 == name):
multiplied = df1[col1] * df2[col2]
Where multiplied
is a series.
Upvotes: 0