Search code examples
pythonpandasdataframeconcatenation

how to Add 2 columns from a dataframe to another while indexes do Not match


i have 2 Data frames that have different length. first one has 1200 rows and the other only 1 the first one is sth like this.

           Date       Open       High        Low      Close  Adj Close  Volume
       2012-01-09  70.40 50.20  9.40      71.5          1.8      1.8       9447.0

the second one looks like this

Name  Marcet Cap.   Symbol   Symbol2    Boerse Info.   Periode    ISIN         WKN 
Once      1         tpp.us     NaN             1          5Y    US010001      999000      

i only want to add (append) 2 columns to the first one, which are ISIN and WKN.

          Date       Open       High      Low      Close  Adj Close  Volume  ISIN   WKN  
       2012-01-09  70.40 50.20  9.40      71.5     1.8      1.8       944   US0101 999000            

i already tried Merge() and Concat, however i got an KeyError and also i tried this which doesn't work.

first['ISIN']=second['ISIN'].values

how can i add 2 columns to the other DF?


Solution

  • Assign value by values[0] instead of values

    import pandas as pd
    import io
    
    data_string = """ Date       Open       High        Low      Close  Adj_Close  Volume
           2012-01-09  70.40 50.20  9.40      71.5          1.8             9447.0
           2012-01-10  70.40 50.20  9.40      71.5          1.8             9447.0"""
    
    first = pd.read_csv(io.StringIO(data_string), sep='\s+')
    
    data_string = """Name  Marcet_Cap.   Symbol   Symbol2    Boerse_Info.   Periode    ISIN         WKN 
    Once      1         tpp.us     NaN             1          5Y    US010001      999000  """
    second = pd.read_csv(io.StringIO(data_string), sep='\s+')
    
    first['ISIN'] = second['ISIN'].values[0]  # work
    first['WKN'] = second['WKN'].values[0]  # work
    
    print(first)  # print sample result
             Date  Open  High  Low  Close  Adj_Close  Volume      ISIN     WKN
    0  2012-01-09  70.4  50.2  9.4   71.5        1.8  9447.0  US010001  999000
    1  2012-01-10  70.4  50.2  9.4   71.5        1.8  9447.0  US010001  999000