从Pandas系列的价值中寻找钥匙

2024-10-01 07:42:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,它的价值在熊猫系列中。我想创建一个新的序列,它将在一个序列中查找一个值,并返回一个带有关联键的新序列。示例:

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']作为新列名的所需结果:

^{pr2}$

由于数据的性质,我必须手动生成nmdict,如图所示。我尝试过this,但由于数组的长度不同,无法反转我的nmdict。在

更重要的是,我认为我的方法可能是错误的。我来自Excel,正在考虑vlookup解决方案,但是根据this answer,我不应该以这种方式使用字典。在

感谢您的回答。在


Tags: indfforif字典序列listseason
3条回答

您可以使用dictionary comprehension创建国家dictionary

country_id = df.season.str.split().str.get(0).drop_duplicates()
country_dict = {c: ('Norway' if c.startswith('N') else 'Sweden') for c in country_id.values}

获得:

^{pr2}$

这对两个国家都适用,否则您可以以类似的方式apply自定义{}:

def country_dict(country_id):
    if country_id.startswith('S'):
        return 'Sweden'
    elif country_id.startswith('N'):
        return 'Norway'
    elif country_id.startswith('XX'):
        return ...
    else:
        return 'default'

不管怎样,map使用pandasstring方法提取的dictionaryseasoncolumn部分:

df['country'] = df.season.str.split().str.get(0).map(country_dict)


       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

我已经做了一个冗长的方式,让你贯彻到底。在

首先,让我们定义一个函数来确定值“country”

In [4]: def get_country(s):
   ...:     if 'Nor' in s:
   ...:         return 'Norway'
   ...:     if 'S' in s:
   ...:         return 'Sweden'
   ...:     # return 'Default Country' # if you get unmatched values

In [5]: get_country('Sven')
Out[5]: 'Sweden'

In [6]: get_country('Norv')
Out[6]: 'Norway'

我们可以使用map对每一行运行get_country。Pandas数据帧还有一个^{},其工作原理类似*。在

^{pr2}$

现在我们将这个结果赋给名为“country”的列

In [8]: df['country'] = map(get_country, df['season'])

让我们来看看最终结果:

In [9]: df
Out[9]: 
       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

*使用apply()以下是它的外观:

In [16]: df['country'] = df['season'].apply(get_country)

In [17]: df
Out[17]: 
       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

可扩展性更强的国家匹配器

仅限伪代码:)

# Modify this as needed
country_matchers = {
    'Norway': ['Nor', 'Norv'],
    'Sweden': ['S', 'Swed'], 
}

def get_country(s):
    """
    Run the passed string s against "matchers" for each country
    Return the first matched country
    """
    for country, matchers in country_matchers.items():
        for matcher in matchers:
            if matcher in s:
                return country

IIUC,我会做以下事情:

df['country'] = df['season'].apply(lambda x: 'Norway' if 'No' in x else 'Sweden' if 'S' in x else x)

相关问题 更多 >