Merge a list of pandas dataframes

后端 未结 1 1448
夕颜
夕颜 2020-12-02 14:31

There has been many similar questions but none specifically to this.

I have a list of data frames and I need to merge them together using a unique column (date

相关标签:
1条回答
  • 2020-12-02 15:14

    You can use reduce function where dfList is your list of data frames:

    import pandas as pd
    from functools import reduce
    reduce(lambda x, y: pd.merge(x, y, on = 'Date'), dfList)
    

    As a demo:

    df = pd.DataFrame({'Date': [1,2,3,4], 'Value': [2,3,3,4]})
    dfList = [df, df, df]
    dfList
    
    # [   Date  Value
    #  0     1      2
    #  1     2      3
    #  2     3      3
    #  3     4      4,    Date  Value
    #  0     1      2
    #  1     2      3
    #  2     3      3
    #  3     4      4,    Date  Value
    #  0     1      2
    #  1     2      3
    #  2     3      3
    #  3     4      4]
    
    reduce(lambda x, y: pd.merge(x, y, on = 'Date'), dfList)
    #   Date  Value_x  Value_y  Value
    # 0    1        2        2      2
    # 1    2        3        3      3
    # 2    3        3        3      3
    # 3    4        4        4      4
    
    0 讨论(0)
提交回复
热议问题