panda通过部分字符串将列的匹配大小分配给数组维度

2024-05-28 18:15:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的数据帧:

  Postcode         Country
0  PR2 6AS  United Kingdom
1  PR2 6AS  United Kingdom
2  CF5 3EG  United Kingdom
3  DG2 9FH  United Kingdom

我创建了一个基于部分字符串匹配的新列:

^{pr2}$

我希望通过“Postcode”上的部分字符串匹配来指定“In_Preston”列。我尝试以下方法:

mytestdf.loc[(mytestdf[mytestdf['Postcode'].str.contains("PR2")]), 'In_Preston'] = "TRUE"

但这将返回错误“无法将大小为3的序列复制到维数为2的数组轴”

我再次查看我的代码,认为问题是我从数据帧的一部分中选择了一部分数据帧。因此我改为

mytestdf.loc[(mytestdf['Postcode'].str.contains("PR2")]), 'In_Preston'] = "TRUE"

但是我的翻译告诉我这是不正确的语法,尽管我不明白为什么。在

我的代码或方法有什么错误?在


Tags: 数据方法字符串intrue错误locunited
1条回答
网友
1楼 · 发布于 2024-05-28 18:15:35

您需要移除内部过滤器:

mytestdf.loc[mytestdf['Postcode'].str.contains("PR2"), 'In_Preston'] = "TRUE"

另一个解决方案是使用^{}

^{pr2}$

但是如果想要指定布尔值Trues和Falses:

mytestdf['In_Preston'] = mytestdf['Postcode'].str.contains("PR2")
print (mytestdf)
  Postcode         Country  In_Preston
0  PR2 6AS  United Kingdom        True
1  PR2 6AS  United Kingdom        True
2  CF5 3EG  United Kingdom       False
3  DG2 9FH  United Kingdom       False

编辑人^{}

如果只想检查Postcode的开头:

mytestdf.Postcode.str.startswith('PR2')

或添加regex^作为字符串的开头:

mytestdf['Postcode'].str.contains("^PR2")

相关问题 更多 >

    热门问题