1

I have two distinct Python DataFrames (i.e., with a size of 2*2) as follows:

Mangoes Apples Mangoes Apples 

and,

1 0 0 1 

I intend to generate a third DataFrame, so that the output could be:

Mangoes 0 0 Apples 

Obviously, i can't multiply both of these Data Frames (i wish i could have done). So, what should be the best way of doing this? Is this something that can be done by Concatenation? or should i start iterating item-by-item for each DataFrame and store the values into a third DataFrame.

2 Answers 2

1

Assuming that both DFs have the same column names and indexes:

In [123]: d1[d2.eq(1)].combine_first(d2) Out[123]: 0 1 0 Mangoes 0 1 0 Apples 

Source DFs:

d1:

In [124]: d1 Out[124]: 0 1 0 Mangoes Apples 1 Mangoes Apples 

d2:

In [125]: d2 Out[125]: 0 1 0 1 0 1 0 1 
Sign up to request clarification or add additional context in comments.

Comments

0

One possible way may be as following:

print(df1) 

Output:

 0 1 0 Mangoes Apples 1 Mangoes Apples 

Other dataframe:

print(df2) 

Output:

 0 1 0 1 0 1 0 1 

Then:

df_new = (df1*df2).replace('',0) print(df_new) 

Output:

 0 1 0 Mangoes 0 1 0 Apples 

4 Comments

Thank you for the guidance. I have tried using this way, and am getting an error, "TypeError: can't multiply sequence by non-int of type 'str'".
@John The possible reason is data type of df2 is not integer or float instead it is string. So, the error is about trying to multiply two string. Can you verify data type for df2 in above example? You can try converting entire df2 to numeric by df2 = df2.apply(pd.to_numeric) and see if df_new = (df1*df2).replace('',0) works. To make simple test, you can try running 'mangoes' * 1 and compare to 'mangoes' * '1'. The later will possibly give same error as you mentioned.
Yes, it was the problem with data type of d2 ... its resolved. By the way, could you kindly elaborate a bit on this line ... df_new = (df1*df2).replace(' ',0) ... what exactly this (' ', 0) was doing
@John if you remove .replace('',0) from the line of code, then you will see empty cells i.e. to make simple test you can try: 'mangoes' * 0 will give ''. So, replacing those empty cells with 0. If it resolved your problem, you can accept the answer if you would like. Happy Coding.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.