【问题标题】:create columns from another using condition从另一个使用条件创建列
【发布时间】:2020-12-14 03:38:29
【问题描述】:

我有 Vendor 和 stores 等列。vendor 有 amazon、lowes、walmart 等值,stores 包括 NYC、WDC、CAL 等。 我想要两列,即 amazon_stores 和 otherVendor_stores。 amazon_stores 将具有所有亚马逊商店的值 并且 otherVendor_stores 将具有其他供应商商店的值。

【问题讨论】:

标签: python pandas


【解决方案1】:

根据您的描述简单使用np.where()

vendor = "amazon,lowes,walmart".split(",")
stores = "NYC,WDC,CAL".split(",")
df = pd.DataFrame([{"vendor":v, "stores":s} for v in vendor for s in stores ])

df = df.assign(
    amazon_store=lambda x: np.where(x["vendor"]=="amazon", x["stores"], ""),
    othervendor_store=lambda x: np.where(x["vendor"]!="amazon", x["stores"], ""),
)

输出

  vendor stores amazon_store othervendor_store
  amazon    NYC          NYC                  
  amazon    WDC          WDC                  
  amazon    CAL          CAL                  
   lowes    NYC                            NYC
   lowes    WDC                            WDC
   lowes    CAL                            CAL
 walmart    NYC                            NYC
 walmart    WDC                            WDC
 walmart    CAL                            CAL

【讨论】:

    猜你喜欢
    • 2017-12-28
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多