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

Time:08-11

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?

CodePudding user response:

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

CodePudding user response:

as I understood correctly you have 2 dataframes. First Dataframe has 1200 rows Second Dataframe has 1 row

and you want to add 2 new columns in first dataframe and the values of those columns should be values of the last 2 columns of the second dataframe.

Because the dataframes have different number of rows, first you should create 2 lists with same size of the first dataframe and then add to first one.

col1 = [seconddataframe['ISIN'][0] for i in range(len(firstdataframe))]

col2 = [seconddataframe['WKN'][0] for i in range(len(firstdataframe))]

firstdataframe['ISIN'] = col1

firstdataframe['WKN'] = col2

just put the name of both dataframes in correct places. I hope it helps

Best wishes

  • Related