Python Pandas merge only certain columns

后端 未结 5 550
小蘑菇
小蘑菇 2020-12-12 12:33

Is it possible to only merge some columns? I have a DataFrame df1 with columns x, y, z, and df2 with columns x, a ,b, c, d, e, f, etc.

I want to merge the two DataFr

5条回答
  •  感情败类
    2020-12-12 13:06

    You can use .loc to select the specific columns with all rows and then pull that. An example is below:

    pandas.merge(dataframe1, dataframe2.iloc[:, [0:5]], how='left', on='key')
    

    In this example, you are merging dataframe1 and dataframe2. You have chosen to do an outer left join on 'key'. However, for dataframe2 you have specified .iloc which allows you to specific the rows and columns you want in a numerical format. Using :, your selecting all rows, but [0:5] selects the first 5 columns. You could use .loc to specify by name, but if your dealing with long column names, then .iloc may be better.

提交回复
热议问题