python - 如果另一列中的行满足条件则填充 nan

标签 python pandas dataframe null

我有以下数据框:

df=pd.DataFrame({'state':['AL','WI','FL','NJ','BM'],'country':['USA','USA','','','']})

如果相应的州行位于州列表之后,我将尝试将我的国家/地区列填写为“美国”:

states = ['AL', 'WI', 'AZ', 'FL', 'NJ', 'CO', 'CT', 'NY']

我查看了以下相关的 SO 帖子: Python Dataframe filling NaN values using information from other columns

认为问题是相似的,我无法对我的情况使用 apply 函数,因为我不知道如何检查另一个列值是否在值列表中。我尝试了以下(不成功)代码:

 df['country'] = values.where(df['country'] == np.nan and df['state'] in states, others=df['country'])
    ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

最佳答案

假设空格是 np.nan ,如果不是,你可以用 df=df.replace('',np.nan) 替换,你可以使用 numpy.where()为了更快获得结果:

df.country=np.where(df.state.isin(states),df.country.fillna('USA'),df.country)
print(df)

  state country
0    AL     USA
1    WI     USA
2    FL     USA
3    NJ     USA
4    BM     NaN

关于python - 如果另一列中的行满足条件则填充 nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55051739/

相关文章:

python - 哪里有 Gmpy 文档?

python - Pandas 面板中的 bool 掩码

python - 使用 apply 函数 pandas 更正日期

python - Pandas :使用组创建新列意味着以另一列为条件

python - 使用 Pandas 基于正则表达式分离列数据

python - pandas 在每个组中找到满足特定条件的行的索引并为这些行分配值

python - 如何在python中获取模块中的所有对象?

python - 使用 Python 从 Google 文档中删除资源

python - sqlite3 数据类型中的拼写错误但仍然有效,为什么?

python - 将 Pandas 系列和数据框对象转换为 numpy 数组