【发布时间】: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')会更合适