简体   繁体   中英

Merging rows from different dataframes together

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM