![](/img/trans.png)
[英]If value from dictionary is in dataframe, return specific corresponding key
[英]Searching value in a dataframe and then putting corresponding value from dictionary in a new coloumn
我有一個帶有一列名稱的數據框,我還有另一個字典,該字典以名稱作為鍵和與之相關的值。我想在數據框中搜索一個名稱,並在字典中添加一個對應的新列。
my dictionary
fruits={'mango':1,'apple':2,'guava':0,'nut':1}
my dataframe
Fruit
mango
apple
guava
nut
預期產量
Fruit Frequency
mango 1
apple 2
guava 0
nut 1
數據框已經在那里,我只想將值與對應的元素映射
另外,如果我的字典中的鍵值對比我的原始數據幀多,如何將鍵和相應的值添加到數據幀。
假設我的數據框是
Fruit
mango
apple
現在我只想吃堅果而不是番石榴,因為它的值為0
所以預期的輸出將是
Fruit Count
mango 1
apple 2
nut 1
在第一部分中,使用map
/ replace
df
Fruit
0 mango
1 apple
2 guava
3 nut
df['Frequency'] = df.Fruit.map(fruits)
df['Frequency'] = df.Fruit.replace(fruits) # alternative to map
df
Fruit Frequency
0 mango 1
1 apple 2
2 guava 0
3 nut 1
對於第二部分,您可以執行設置差異並將其與原始-
df
Fruit
mango
apple
i = df.Fruit
j = pd.Series(list(set(fruits.keys()).difference(i)))
df = pd.concat([i, j], ignore_index=True).to_frame('Fruit')
df
Fruit
0 mango
1 apple
2 nut
3 guava
要刪除頻率== 0的行,請使用布爾索引-
df
Fruit Frequency
0 mango 1
1 apple 2
2 guava 0
3 nut 1
df = df[df.Frequency.gt(0)]
df
Fruit Frequency
0 mango 1
1 apple 2
3 nut 1
或者,使用eval
/ query
。
df.query("Frequency > 0")
Fruit Frequency
0 mango 1
1 apple 2
3 nut 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.