【问题标题】:Pandas Assign column by partial string match size to array dimension errorPandas 按部分字符串匹配大小将列分配给数组维度错误
【发布时间】:2018-04-09 19:13:08
【问题描述】:

我有一个这样的数据框:

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

我根据部分字符串匹配创建要分配的新列:

mytestdf['In_Preston'] = "FALSE"

mytestdf

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

我希望通过“邮政编码”上的部分字符串匹配来分配“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"

但我的解释器告诉我这是不正确的语法,虽然我不明白为什么。

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

【问题讨论】:

  • mytestdf.Postcode.str.startswith('PR2') 会更合适

标签: python string pandas


【解决方案1】:

您需要移除内部过滤器:

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

另一种解决方案是使用numpy.where:

mytestdf['In_Preston'] = np.where(mytestdf['Postcode'].str.contains("PR2"), 'TRUE', 'FALSE')
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

但如果要分配布尔值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

comment of Zero编辑:

如果只想检查 Postcode 的开头:

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

或者添加正则表达式^作为字符串的开头:

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

【讨论】:

  • Answer 还可以与许多替代选项一起使用以进行改进。很好的回应,非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
  • 2021-12-07
  • 2022-11-14
  • 2017-04-02
  • 2022-01-24
  • 1970-01-01
  • 2017-12-12
相关资源
最近更新 更多