匹配 Python 中的字符串元素(应用函数)

Matching string elements in Python (apply function)

我有 Twitter 数据,我正在尝试 return 所有与用户自我描述的位置相匹配的州缩写。我已经创建了一个匹配函数并将其应用于我的数据框,但出于某种原因我没有 returning 任何匹配项(所有 NaN),尽管原始数据中有状态缩写。

我的州列表包括所有 50 个州

states = ['AL','AK','AZ','AR','CA'...]

我的数据框的一个小样本如下所示:

        user_location            text
0   CO                           australia to manufacture covid vaccine and g...
1   Seattle, WA                  coronavirusvaccine coronavaccine covidvaccine ...
2   nan                          deaths due to covid in affected countries re...
3   Atlanta, GA                  subhashree stay safe di amp da

我创建了以下嵌套循环函数来尝试 return 我的状态列表中的位置与 user_location 列的匹配:

def match(user_location):
    for state in states:
        if state in tweets2.user_location:
            return state
        else:
            return np.nan

然后我通过应用我的函数创建了 returned 匹配的新列:

tweets2['State'] = tweets2['user_location'].apply(match)

但是,当我知道 user_location 列中肯定有州缩写时,我得到的 returned 都是 NaN 值。

我使用以下代码进行了检查:

tweets2['State'].notnull().value_counts()

如果能帮助解决这个问题,我们将不胜感激!

在您的代码中,一旦找不到一个状态,您就会 returning nan,如下所示

def match(user_location):
    for state in states:
        if state in tweets2.user_location:
            return state
        else:
            return np.nan

您应该将其更改为 return 仅在检查所有状态后才为 nan。为此你可以这样编码,

def match(user_location):
    for state in states:
        if state in tweets2.user_location:
            return state
     return np.nan

您 return 值总是在循环的第一次迭代之后。尽量避免在循环内使用 return。让我们重建你的循环:

def match(user_location):
    user_state = np.nan
    for state in states:
        if state in user_location:
            user_state = state
            break
    return user_state

print(match(tweets2.user_location))

你可以用集合做一些更优雅的事情。如果您将 states 设为一个集合,那么您可以执行以下操作:states.intersection(tweets2.user_location) 这将 return 一组存在于两个集合中的项目。