【问题标题】:Looping through dataframe to extract substrings that match dictionary循环遍历数据框以提取匹配字典的子字符串
【发布时间】:2016-05-03 03:12:24
【问题描述】:

我正在尝试遍历数据框中的列,如果它包含字典中的值,则使用循环列中的子字符串创建一个新列。更具体地说,如果地址列中的单个行包含州名称和缩写字典中的州,则将州缩写附加到将成为新列的列表中。

以下代码适用于完全匹配,但不扫描行中的子字符串:

import pandas as pd

df = pd.DataFrame((['Austin, Texas',
               'Texas',
               'Seattle, Washington',
               ',,, Texas',
               'Olympia, WA']), columns = ['Place'])

states = {'Texas': 'TX',
      'Washington': 'WA'}

place = df['Place']

results = []

for x in place:
    if x in states:
        results.append(x)
    else:
        results.append(None)

df['State'] = results
df

谢谢!

【问题讨论】:

    标签: python loops pandas dataframe substring


    【解决方案1】:

    嵌套的条件列表推导可以解决问题。您需要在逗号上拆分并使用条来删除空格。

    另外,纽约、纽约(城市、州)可能会导致问题,所以我将结果留在了一个列表中。

    df['results'] = [[state.strip() for state in cell.split(',') 
                      if state.strip() in states] 
                     for cell in df.Place]
    
    df['results2'] = df.results.apply(lambda s: s[-1] if s else '')
    
    >>> df
                     Place       results    results2
    0        Austin, Texas       [Texas]       Texas
    1                Texas       [Texas]       Texas
    2  Seattle, Washington  [Washington]  Washington
    3            ,,, Texas       [Texas]       Texas
    4          Olympia, WA            []            
    

    【讨论】:

    • 我忘了问,你如何用这个返回一个非列表?我认为我的数据中没有纽约,纽约,所以这对我来说应该不是问题。
    • 对不起,我是个害虫,但我收到“名称'单元'未定义”错误?快速的谷歌搜索似乎没有找到任何东西?
    猜你喜欢
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 2021-10-23
    • 2015-10-31
    • 2020-11-04
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    相关资源
    最近更新 更多