首页 > 解决方案 > 在 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

我该如何解决这个问题,非常感谢您的帮助!

标签: pythonpandas

解决方案


我试过这个 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'

推荐阅读