-2

I have two DataFrames: one has string and the other has int. I am trying to multiply these two to generate an algebraic expression:

df1=pd.DataFrame([1,2,3])
df2=pd.DataFrame(["x","y","z"])

Expected Output: enter image description here

How to generate the expression with two different data types?

Ussu20
  • 129
  • 1
  • 12
  • Does this answer your question? [String concatenation of two pandas columns](https://stackoverflow.com/questions/11858472/string-concatenation-of-two-pandas-columns) – G. Anderson Mar 09 '21 at 18:44
  • I Tried this:`df1[0]+"is"+df2[0].map(str)` but got error. – Ussu20 Mar 09 '21 at 18:48
  • Do you want an actual algebraic expression as in sympy or are `df1` just the coefficients for `df2` and you want to print the formula? – user8408080 Mar 09 '21 at 18:49
  • Edited the expected output. These are not coefficients but multiplying factors. – Ussu20 Mar 09 '21 at 18:54
  • Why are using dataframe for this? You can do this by `string concatenation` without using pandas! – ashkangh Mar 09 '21 at 19:01

2 Answers2

1

Try

formula = ""    

# looping through tuples of (x, 1) (y, 2) (z, 3)

for val, var in zip(df1.values,df2.values):

    # formatting the value and variable in the current tuple 
    # and appending to the initially empty formula string

    formula += "{}*{}+".format(val[0], var[0])

dirty quick way to remove last + sign

formula = formula[:-1]

Ari K
  • 434
  • 2
  • 18
0

This should work.

import pandas as pd 

df1=pd.DataFrame([1,2,3])
df2=pd.DataFrame(["x","y","z"])
   
formula = '+'.join([f'{var[0]}*{val[0]}' for val, var in zip(df1.values,df2.values)])
     
print(formula)
norie
  • 9,609
  • 2
  • 11
  • 18