亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過字典在 pandas 中創建新行

如何通過字典在 pandas 中創建新行

Smart貓小萌 2023-12-26 16:58:51
我對 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'}]因此,我需要創建新行并用 0 填充它們(如果品牌為 Null)。它應該看起來像這樣: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},謝謝!
查看完整描述

1 回答

?
慕尼黑5688855

TA貢獻1848條經驗 獲得超2個贊

您可以從數據幀創建多索引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


查看完整回答
反對 回復 2023-12-26
  • 1 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號