我对pandas DataFrame有问题-我不知道如何创建新行并将其与字典合并。
瞬时,我有这个数据框:
shops = [{'Chain': 'SeQu', 'Shop': 'Rimme', 'Location': 'UK', 'Brand': 'Rexona', 'Value': 10},
{'Chain': 'SeQu', 'Shop': 'Rimme', 'Location': 'UK', 'Brand': 'AXE', 'Value': 20},
{'Chain': 'SeQu', 'Shop': 'Rimme', 'Location': 'UK', 'Brand': 'Old Spice', 'Value': 30},
{'Chain': 'SeQu', 'Shop': 'Rimme', 'Location': 'UK', 'Brand': 'Camel', 'Value': 40},
{'Chain': 'SeQu', 'Shop': 'Rimme', 'Location': 'UK', 'Brand': 'Dove', 'Value': 50},
{'Chain': 'SeQu', 'Shop': 'Rum', 'Location': 'USA', 'Brand': 'Rexona', 'Value': 10},
{'Chain': 'SeQu', 'Shop': 'Rum', 'Location': 'USA', 'Brand': 'CIF', 'Value': 20},
{'Chain': 'SeQu', 'Shop': 'Rum', 'Location': 'USA', 'Brand': 'Old Spice', 'Value': 30},
{'Chain': 'SeQu', 'Shop': 'Rum', 'Location': 'USA', 'Brand': 'Camel', 'Value': 40}]
同时,我有一个带有Chain-Brand连接的字典数据框:
chain_brands = [{'Chain': 'SeQu', 'Brand': 'Rexona'},
{'Chain': 'SeQu', 'Brand': 'Axe'},
{'Chain': 'SeQu', 'Brand': 'Old Spice'},
{'Chain': 'SeQu', 'Brand': 'Camel'},
{'Chain': 'SeQu', 'Brand': 'Dove'},
{'Chain': 'SeQu', 'Brand': 'CIF'}]
因此,如果品牌为Null,我需要创建新行并用0填充它们。它应该看起来像这样:
output = [{'Chain': 'SeQu', 'Shop': 'Rimme', 'Location': 'UK', 'Brand': 'Rexona', 'Value': 10},
{'Chain': 'SeQu', 'Shop': 'Rimme', 'Location': 'UK', 'Brand': 'AXE', 'Value': 20},
{'Chain': 'SeQu', 'Shop': 'Rimme', 'Location': 'UK', 'Brand': 'Old Spice', 'Value': 30},
{'Chain': 'SeQu', 'Shop': 'Rimme', 'Location': 'UK', 'Brand': 'Camel', 'Value': 40},
{'Chain': 'SeQu', 'Shop': 'Rimme', 'Location': 'UK', 'Brand': 'Dove', 'Value': 50},
{'Chain': 'SeQu', 'Shop': 'Rimme', 'Location': 'UK', 'Brand': 'CIF', 'Value': 0},
{'Chain': 'SeQu', 'Shop': 'Rum', 'Location': 'USA', 'Brand': 'Rexona', 'Value': 10},
{'Chain': 'SeQu', 'Shop': 'Rum', 'Location': 'USA', 'Brand': 'CIF', 'Value': 20},
{'Chain': 'SeQu', 'Shop': 'Rum', 'Location': 'USA', 'Brand': 'Old Spice', 'Value': 30},
{'Chain': 'SeQu', 'Shop': 'Rum', 'Location': 'USA', 'Brand': 'Axe', 'Value': 0},
{'Chain': 'SeQu', 'Shop': 'Rum', 'Location': 'USA', 'Brand': 'Camel', 'Value': 40},
{'Chain': 'SeQu', 'Shop': 'Rum', 'Location': 'USA', 'Brand': 'Dove', 'Value': 0}]
谢谢!
答案 0 :(得分:1)
您可以从chain_brands
数据帧创建多索引,然后将groupby
与reindex
一起使用来解决此问题:
mi = pd.MultiIndex.from_arrays(chain_brands.values.T, names=['Chain', 'Brand'])
s = shops.set_index(['Chain', 'Brand']).\
groupby(['Location', 'Shop']).\
apply(lambda x: x.reindex(mi, fill_value=0)).\
drop(columns=['Location', 'Shop']).\
reset_index()
结果:
Location Shop Chain Brand Value
0 UK Rimme SeQu Rexona 10
1 UK Rimme SeQu Axe 0
2 UK Rimme SeQu Old Spice 30
3 UK Rimme SeQu Camel 40
4 UK Rimme SeQu Dove 50
5 UK Rimme SeQu CIF 0
6 USA Rum SeQu Rexona 10
7 USA Rum SeQu Axe 0
8 USA Rum SeQu Old Spice 30
9 USA Rum SeQu Camel 40
10 USA Rum SeQu Dove 0
11 USA Rum SeQu CIF 20