Python 使用其他条件创建列
我有像Vendor和stores这样的专栏。Vendor有像amazon、lowes、walmart这样的价值观,stores包括NYC、WDC、CAL等。 我想要两列,即亚马逊商店和其他供应商商店。 亚马逊商店将拥有所有亚马逊商店的价值Python 使用其他条件创建列,python,pandas,Python,Pandas,我有像Vendor和stores这样的专栏。Vendor有像amazon、lowes、walmart这样的价值观,stores包括NYC、WDC、CAL等。 我想要两列,即亚马逊商店和其他供应商商店。 亚马逊商店将拥有所有亚马逊商店的价值 其他供应商的商店将具有其他供应商商店的价值。根据您的描述简单使用np.where() vendor = "amazon,lowes,walmart".split(",") stores = "NYC,WDC,C
其他供应商的商店将具有其他供应商商店的价值。根据您的描述简单使用
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
A会增加你得到有用答案的机会。