我有一個產品陣列,其看起來像見下表:使用lambda的詞典中特定鍵的值?
+---------------------------+--------------------------------+--------------------------------+ | name | review | word_count | +---------------------------+--------------------------------+--------------------------------+ | | | {'and': 5, 'wipes': 1, | | Planetwise | These flannel wipes are OK, | 'stink': 1, 'because' : 2, ... | | Flannel Wipes | but in my opinion ... | | | | | | +---------------------------+--------------------------------+--------------------------------+ | | | {'and': 3, 'love': 1, | | Planetwise | it came early and was not | 'it': 2, 'highly': 1, ... | | Wipes Pouch | disappointed. i love ... | | | | | | +---------------------------+--------------------------------+--------------------------------+ | | | {'shop': 1, 'noble': 1, | | | | 'is': 1, 'it': 1, 'as': ... | | A Tale of Baby's Days | Lovely book, it's bound | | | with Peter Rabbit ... | tightly so you may no ... | | | | | | +---------------------------+--------------------------------+--------------------------------+
基本上word_count
列包含字的dictionary(key : value)
一個發生的review
列句子。
現在我想建立一個新的列名and
它應該包含在word_count
字典and
值,如果and
存在作爲word_count
列鍵,則該值,如果它沒有作爲一個關鍵的存在,則0
。
對於第3行中的新and
列看起來是這樣的:
+------------+
| and |
+------------+
| |
| 5 |
| |
| |
+------------+
| |
| 3 |
| |
| |
+------------+
| |
| 0 |
| |
| |
+------------+
我寫了這個代碼和它的正常工作:
def wordcount(x):
if 'and' in x:
return x['and']
else:
return 0
products['and'] = products['word_count'].apply(wordcount);
我的問題:有什麼辦法我可以使用lambda
來做到這一點?
什麼我迄今所做的是:
products['and'] = products['word_count'].apply(lambda x : 'and' in x.keys());
這僅返回0
或1
列。我可以在上面的行中添加什麼,以便products['and']
包含值and
作爲密鑰存在時的密鑰products['word_count']
?
我正在使用ipython notebook和graphlab。