【问题标题】:pandas - combine two pandas dataframes with list columns, but combine the lists from the most recent timestampspandas - 将两个 pandas 数据框与列表列组合在一起,但将最近时间戳中的列表组合起来
【发布时间】:2023-02-23 02:53:48
【问题描述】:

假设我有数据框 A 和 B,索引为time,列表列为food。这两个数据框都类似于历史日志,即我当时拥有的水果和蔬菜:

A:

            food
time
2021-08-20  ["apple","orange"] 
2021-08-28  ["apple","orange","banana"]

乙:

            food
time
2021-08-19  ["squash"] 
2021-08-24  ["squash","carrot"] 
2021-08-29  ["carrot"]

我怎样才能结合这两个数据框,以便它同时跟踪水果和蔬菜?

            food
time
2021-08-19  ["squash"]
2021-08-20  ["apple","orange","squash"] 
2021-08-24  ["apple","orange","squash","carrot"]
2021-08-28  ["apple","orange","banana","squash","carrot"]
2021-08-29  ["apple","orange","banana","carrot"]

本质上,我想合并行,并且对于每一行,合并该时间戳之前两个最新条目的食物。保证 A 和 B 中的食物项不重叠,并且 A 和 B 之间的时间戳不重叠。

我尝试直接使用 pd.concat([A,B]) ,但它不会组合食物。

【问题讨论】:

    标签: python pandas concatenation


    【解决方案1】:

    我相信这就是您要找的:

    # Create the first data frame
    df_a = pd.DataFrame({
        'date': ['2021-08-20', '2021-08-28'],
        'foods': [['apple', 'orange'], ['apple', 'orange', 'banana']]
    })
    
    # Create the second data frame
    df_b = pd.DataFrame({
        'date': ['2021-08-19', '2021-08-20', '2021-08-29'],
        'foods': [['squash'], ['squash', 'carrot'], ['carrot']]
    })
    
    # Merge the two data frames on the date column
    merged = pd.merge(df_a, df_b, on='date', how='outer')
    
    # Concatenate the food item lists
    def concat_foods(row):
        foods_x = row['foods_x'] if isinstance(row['foods_x'], list) else []
        foods_y = row['foods_y'] if isinstance(row['foods_y'], list) else []
        return list(set(foods_x + foods_y))
    
    merged['foods'] = merged.apply(concat_foods, axis=1)
    
    # Remove the original food item columns
    merged = merged.drop(['foods_x', 'foods_y'], axis=1)
    
    # Sort the data frame by date
    merged = merged.sort_values('date')
    

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 2023-02-20
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2022-10-25
      相关资源
      最近更新 更多