【问题标题】:How to replace pd.Series list values with dictionary values如何用字典值替换 pd.Series 列表值
【发布时间】:2023-03-10 14:20:01
【问题描述】:

用 NLTK 提取词干后,得到字典:

> {'golden': 'gold',  'wonderfully': 'wonder',  'damaging': 'damag', 
> 'useless': 'use',  'toys': 'toy',  'ducks': 'duck'}

所以我想替换 pd.Series 中的现有单词(其中值是列表):

0              ['want', 'buy', 'toys', 'ducks']
1                                    ['street']
2     ['damaging', 'toys', 'isolating', 'toys']
3                       ['useless', 'clothing']

我希望输出为(替换玩具为玩具等。如字典中所示):

0                ['want', 'buy', 'toy', 'duck']
1                                    ['street']
2          ['damag', 'toy', 'isolating', 'toy']
3                           ['use', 'clothing']

【问题讨论】:

    标签: python-3.x pandas dictionary replace series


    【解决方案1】:

    尝试explode 然后replaceagg 返回,d 是你的字典

    out = s.explode().replace(d).groupby(level=0).agg(list)
    

    【讨论】:

    • 该解决方案确实有效。只需使用d 定义查找字典(可能不清楚)。
    【解决方案2】:

    你可以使用apply:

    import pandas as pd
    
    # the replacement dictionary
    replacements = {'golden': 'gold', 'wonderfully': 'wonder',
                    'damaging': 'damag', 'useless': 'use', 'toys': 'toy', 'ducks': 'duck'}
    
    # setup of the Series
    s = pd.Series([['want', 'buy', 'toys', 'ducks'],
                   ['street'],
                   ['damaging', 'toys', 'isolating', 'toys'],
                   ['useless', 'clothing']])
    
    
    def replace(lst, repl):
        """This function receives a list and replaces the elements with the values of the keys in repl"""
        return [repl.get(e, e) for e in lst]
    
    
    out = s.apply(replace, args=(replacements,))
    print(out)
    

    输出

    0          [want, buy, toy, duck]
    1                        [street]
    2    [damag, toy, isolating, toy]
    3                 [use, clothing]
    dtype: object
    

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 2019-04-07
      • 2018-03-08
      • 1970-01-01
      • 2021-09-22
      • 2019-12-07
      • 1970-01-01
      • 2018-02-08
      相关资源
      最近更新 更多