python - 如果列表中有文本,则用值替换某些文本

标签 python pandas dataframe

我只是在快速了解 Pandas,无法解决一个问题。我有一份纽约州的县名单。如果该县是 5 个行政区之一,我想将县名更改为纽约,否则我就不管它了。以下给出了思路,但不正确。

编辑 - 因此,如果前几行的县列中的县在更改前是奥尔巴尼、阿勒格尼、布朗克斯,则更改后它们将是纽约州奥尔巴尼、阿勒格尼

# clean up county names
# 5 boroughs must be combined to New York City
# eliminate the word county
nyCounties = ["Kings", "Queens", "Bronx", "Richmond", "New York"]

nypopdf['County'] = ['New York' for nypopdf['County'] in nyCounties else   
nypopdf['County']]

最佳答案

一个小模型:

In [44]: c = ['c', 'g']
In [45]: df = pd.DataFrame({'county': list('abccdefggh')})
In [46]: df['county'] = df['county'].where(~df['county'].isin(c), 'N')
In [47]: df
Out[47]:   county
         0      a
         1      b
         2      N
         3      N
         4      d
         5      e
         6      f
         7      N
         8      N
         9      h

所以这是使用 pd.Series.where ~df['county'].isin(c) 选择不在列表 c 中的行(开头的 ~ 是'not' 操作),第二个参数是要替换的值(当条件为 False 时)。

为了适合你的例子:

nypopdf['County'] = nypopdf['County'].where(~nypopdf['County'].isin(nyCounties), 'New York')

nypopdf['County'].where(~nypopdf['County'].isin(nyCounties), 'New York', inplace=True)

完整示例:

nypopdf = pd.DataFrame({'County': ['Albany', 'Allegheny', 'Bronx']})
nyCounties = ["Kings", "Queens", "Bronx", "Richmond", "New York"]
print(nypopdf)
      County
0     Albany
1  Allegheny
2      Bronx
nypopdf['County'].where(~nypopdf['County'].isin(nyCounties), 'New York', inplace=True)
print(nypopdf)
      County
0     Albany
1  Allegheny
2   New York

关于python - 如果列表中有文本,则用值替换某些文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53023249/

相关文章:

python - 将 DataFrame 拆分为两个 DataFrame 并过滤这两个 DataFrame 以获得相同的维度

python - 从 pandas DataFrame 导出 LaTeX 表

python date unix 丢失了 1 天

Python Matplotlib - 双 y 轴图中的脊柱着色问题

python - def_list_of_dups(some_list) : 有什么问题

python - 如何重新创建 pandas DataFrame、线条和条形图

缓冲区中的 Python Windows API 转储过程然后进行 REGEX 搜索

python - 如何计算每个项目的平均索引位置

python - 将多个正则表达式与单个列匹配(并将匹配结果制成表格)

python - 将 SpaCy 的 EntityRecognizer 应用于 Pandas 数据框中的列