python - 如果列表中有文本,则将某些文本替换为值
问题描述
我刚刚开始熟悉 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
推荐阅读
- php - 致命错误:未捕获的 SoapFault 异常:[Client] SOAP-ERROR: Encoding: SoapVar has no 'enc_type' property
- android - 我可以从 ObjectBox 的 id 字段中删除 Assignable 属性吗
- jquery - 使用 jquery 在第二个 li 中的 URL 链接
- laravel-5 - 如何更改分页中的url?
- xaml - XAML Xamarin 中的数据模板
- javascript - 为什么我的 javascript 变量在 PHP 中变成了一个数组?
- python - 使用 s3fs(通过 dask)测试模拟 S3 存储桶的行为是意外的
- firebase - 在一个父节点与多个子节点上可观察到 Firebase 角度 5
- java - 如何设置空值?
- reactjs - 在 react-native 中进行突变后如何更新阿波罗商店?