【发布时间】:2016-04-23 21:13:16
【问题描述】:
我有一本字典,其值在熊猫系列中。我想制作一个新系列,它将在系列中查找一个值并返回一个带有关联键的新系列。示例:
import pandas as pd
df = pd.DataFrame({'season' : ['Nor 2014', 'Nor 2013', 'Nor 2013', 'Norv 2013',
'Swe 2014', 'Swe 2014', 'Swe 2013',
'Swe 2013', 'Sven 2013', 'Sven 2013', 'Norv 2014']})
nmdict = {'Norway' : [s for s in list(set(df.season)) if 'No' in s],
'Sweden' : [s for s in list(set(df.season)) if 'S' in s]}
以df['country'] 作为新列名的期望结果:
season country
0 Nor 2014 Norway
1 Nor 2013 Norway
2 Nor 2013 Norway
3 Norv 2013 Norway
4 Swe 2014 Sweden
5 Swe 2014 Sweden
6 Swe 2013 Sweden
7 Swe 2013 Sweden
8 Sven 2013 Sweden
9 Sven 2013 Sweden
10 Norv 2014 Norway
由于我的数据性质,我必须手动创建nmdict,如图所示。我试过this,但无法反转我的nmdict,因为数组的长度不同。
更重要的是,我认为我的方法可能是错误的。我来自 Excel,正在考虑一个 vlookup 解决方案,但根据this answer,我不应该以这种方式使用字典。
感谢任何答案。
【问题讨论】:
标签: python dictionary pandas