merge two files based on common column values

前端 未结 2 1054
清酒与你
清酒与你 2021-01-26 00:26

I have file1 likes:

1 A aa
2 A bb
3 A cc
4 A dd
5 B xx
6 C yy
7 C zz

And a file2:

1 A 11
2 B 22
3 C 33

And I

相关标签:
2条回答
  • 2021-01-26 00:41

    Using pandas will save you a lot of time if you use Python. So if your DataFrames are df1:

       1   2
    0
    1  A  aa
    2  A  bb
    3  A  cc
    4  A  dd
    5  B  xx
    6  C  yy
    7  C  zz
    

    and df2:

       1   2
    0
    1  A  11
    2  B  22
    3  C  33
    

    then you can use merge:

    df1.merge(df2, left_on=1, right_on=1)
    

    to get

       1 2_x  2_y
    0  A  aa   11
    1  A  bb   11
    2  A  cc   11
    3  A  dd   11
    4  B  xx   22
    5  C  yy   33
    6  C  zz   33
    
    0 讨论(0)
  • 2021-01-26 01:01

    Which way is the simplest

    I am not sure what do you mean by simplest. For this problem, you can simply use join:

    join -j 2 -o 1.1 1.2 1.3 2.3 file1 file2
    

    For the given example, the above command generates the desired output. If your file is not sorted, you can also add --nocheck-order option.

    0 讨论(0)
提交回复
热议问题