Home > front end >  Pandas merge not working after using StringIO
Pandas merge not working after using StringIO

Time:12-04

I need to convert a string into a pandas DataFrame to further merge it with another DataFrame, unfortunately the merge is not working.

str_data = StringIO("""col1;col2
one;apple
two;lemon""")

df = pd.read_csv(str_data, sep =";")

df2 = pd.DataFrame([['one', 10], ['two', 15]], columns = ['col1', 'col3'])

df=df.merge(df2, how='left', on='col1')

The resulting DataFrame has on NaN´s in col3 and not the integers from col3 in df2

      col1   col2  col3
0      one  apple   NaN
1      two  lemon   NaN

thanks in advance for recommendations!

CodePudding user response:

For me working well:

from io import StringIO

str_data = StringIO("""col1;col2
one;apple
two;lemon""")

df = pd.read_csv(str_data, sep =";")

df2 = pd.DataFrame([['one', 10], ['two', 15]], columns = ['col1', 'col3'])

df=df.merge(df2, how='left', on='col1')
print (df)
  col1   col2  col3
0  one  apple    10
1  two  lemon    15
  • Related