如何基于熊猫中其他列的唯一值添加行

时间:2020-07-29 11:02:29

标签: pandas

假设我有一个看起来像这样的数据框

enter image description here

对于每个唯一商店,都有6个唯一MRP值 这是1999.,2499.,2699.,2799.,2999.,4499,因此对于某些唯一商店而言,并非所有价格值都意味着这是sales_aty为零。我如何找到那些唯一的商店,如果没有任何价格,然后添加MRP值缺失且销售数量为零的商店

1 个答案:

答案 0 :(得分:0)

使用联接。首先根据您期望的所有组合创建索引。然后尝试加入您的数据框。左联接将使没有数据的索引值保留为空。应用逻辑来填充空值以满足您的需求。

import itertools
import pandas as pd
store_ids = df['STORE'].drop_duplicates()
mrp_values = (1999, 2499, 2699, 2799, 2999)
keys = itertools.product(store_ids, mrp_values)
temp = pd.DataFrame.from_records([{'store_id': store_id, 'mrp': mrp_value}
                                  for store_id, mrp_value in keys])
result = temp.merge(df, how="left", left_on=["store_id", "mrp"],
                                    right_on=["STORE", "MRP"])
# apply null-handling logic to result...