python - 在 Python Pandas 中,如何搜索列元素是否包含前 2 位数字
问题描述
我对 Python 还很陌生,目前我正在尝试构建一个函数来搜索列中元素的前 2 位数字,如果为真,则返回带有新标题的结果,例如区域
例如,
Adres AreaCode Region
0 SArea 123191 A
1 BArea 122929 A
2 AArea 132222 B
我希望该函数仅搜索 AreaCode 的前 2 位数字,这将为我提供结果以及 Region 的新标头,该标头根据 AreaCode 的前 2 位数字对 Region 进行分类。所以在这种情况下,12 会给我 A,而 13 会给我 B
我已经试过了
df.loc[df.AreaCode == 123191, 'Region'] = 'A'
这适用于整个 AreaCode 但我不知道如何修改它以便能够根据前 2 位数字进行搜索。
我试过这个
df.loc[df.AreaCode.str.contains == 12, 'Region' ] = 'A'
但它给了我错误:
AttributeError: Can only use .str accessor with string values,
which use np.object_ dtype in pandas
我该如何解决这个问题,非常感谢您的帮助!
解决方案
我试过这个 df.loc[df.AreaCode.str.contains == 12, 'Region' ] = 'A' 但它给了我错误:AttributeError: Can only use .str accessor with string values, which use np.object_大熊猫中的dtype
您可以简单地将其转换为字符串,然后使用相同的代码:
df.loc[df.AreaCode.astype(str).str.startswith('12'), 'Region' ] = 'A'
推荐阅读
- postgresql - Docker Compose postgres 9.6 初始化数据库
- vue-apollo - Vue Apollo 项目 - 拥有单独的服务是共享状态的好方法吗?
- mysql - 如何修复 SQL 错误 (1248):每个派生表都必须有自己的别名
- python - 当满足 2 个标准时,如何仅总结基于值的值?
- excel - 粘贴另一个工作表中的前导公共子字符串
- javascript - 如何在前端 Web 应用程序中隐藏测验的答案?
- ruby-on-rails - ActiveRecord 在双向线程中选择第一条消息
- excel - 使用 AGGREGATE 函数提取数组中的最大值会引发错误
- python - 显示 subprocess.Popen 的输出,就像在终端中运行一样
- flutter - 如何临时更改 Flutter 小部件中的文本颜色(并返回)?