如何根据条件从数据框列名称填充列值?

时间:2019-08-12 18:08:45

标签: python pandas dataframe series pandasql

我有一个包含这些列的数据框-<script type="text/x-magento-init"> { "#product_addtocart_form": { "configurable": { "spConfig": {"attributes":{"93":{"id":"93","code":"color","label":"Color","options":[{"id":"8243","label":"Helloworld","products":["97460","97459"]}],"position":"0"},"148":{"id":"148","code":"codish","label":"Codish","options":[{"id":"4707","label":"12.5","products":[]},{"id":"2724","label":"13","products":[]},{"id":"4708","label":"13.5","products":[]}],"position":"1"}},"template":"EUR <%- data.price %>","optionPrices":{"97459":{"oldPrice":{"amount":121},"basePrice":{"amount":121},"finalPrice":{"amount":121},"tierPrices":[]}},"prices":{"oldPrice":{"amount":"121"},"basePrice":{"amount":"121"},"finalPrice":{"amount":"121"}},"productId":"97468","chooseText":"Choose an Option...","images":[],"index":[]}, "gallerySwitchStrategy": "replace" } } } </script>

我需要根据<script type="text/x-magento-init">列中的值填充新列-spConfig

如果\"spConfig\"\: (.*?) = 1,则用maxlevel, level1id, level2id, level3id填充newcol_value

如果maxlevel = 2,则用maxlevel填充newcol_value

如果level1id = 3,则用maxlevel填充newcol_value

我尝试过这个。

level2id

但是当maxlevel给出系列时,出现以下错误。

  

TypeError:“系列”对象是可变的,因此不能进行散列处理

如何基于newcol_value列中的值来填充level3id值?

1 个答案:

答案 0 :(得分:1)

您应该使用lookup

d={'level1id':1, 'Level2ID':2, 'level3id':3, 'level4id':4, 'level5id':5}


df=df.rename(columns=d)
df['New']=df.lookup(df.index,df.maxlevel)