1
votes

I have two Dataframes: one with columns "Name", "Year" and "Type" and the other one with different parameters. There are 4 different types and each one has his specific parameters. Now i need to merge them together.

My approach is to use a if-function to find out the "type". For example in row two of df3 i have type 'a'. The parameters for type 'a' are in row 3 of df4. I tried to connect them with the following code:

df3.ix[[2]]
s1 = df3.ix[[2]]
s2 = df4.ix[[3]]
result = pd.concat([s1, s2], axis=1)

My problem is now, that the parameters are in a seperate row and not added to row 2. Is there a chance to merge them together in one row? Thanks for your answers!

1
Post raw input data for both dfs, your code to create them and the desired output, at the moment your question is very vague - EdChum
i import the dfs directly from two different excel-files - Tobias

1 Answers

1
votes

If df3 has a Type column and df4 has a type column, then the two DataFrames can be merged with

pd.merge(df3, df4, left_on='Type', right_on='type')

This is by default an inner join.


In [13]: df3
Out[13]: 
  Name  Year   Type
1    A  2012   boat
2    B  2013    car
3    C  2011  truck
4    D  2013   boat

In [14]: df4
Out[14]: 
    type  Parameter1  Parameter2  Parameter3
0   boat           2           8           7
1    car           1           9           3
2  truck           5           4           2

In [15]: pd.merge(df3, df4, left_on='Type', right_on='type')
Out[15]: 
  Name  Year   Type   type  Parameter1  Parameter2  Parameter3
0    A  2012   boat   boat           2           8           7
1    D  2013   boat   boat           2           8           7
2    B  2013    car    car           1           9           3
3    C  2011  truck  truck           5           4           2

Note that if the column names matched exactly, then

pd.merge(df3, df4)

would merge on column names shared in common by default.