我在MacOSSierra10.12.6上的Spyder3.2.3上用Python3.6编程。在
我在数据框df
中有一列,其中包含澳大利亚城镇的列表和其他信息。感兴趣的列是suburbs
df["suburbs"]
Apollo Bay (Tas.)
Apollo Bay (Vic.)
Apoinga
ACT Remainder - Belconni
我还有一份名单states
,其中包括澳大利亚的州。在
我的目标是查看来自df["suburbs"]
的郊区是否包含列表states
中的任何状态,如果是,那么它将返回df["state"]
列中的状态。在
所以,目前我的解决方案是使用for loop和if语句,但是出于某种原因,我的for loop和if语句即使匹配也会返回not found
。我当前的for循环和if语句如下:
for suburb in df["suburbs"].str.upper():
for state in states:
if state in suburb:
df["state"] = state
else:
df["state"] = "not found"
这个又回来了
not found
not found
not found
not found
我注意到的另一件事是在Spyder的variable explorer部分,上面的代码分别创建了两个变量suburb
和{ACT Remainder - Belconni
和{
但是,如果我不创建一个新的列state
,而只使用print
函数来查看子字符串是否匹配,则表明它确实有效。代码如下:
for suburb in test["suburbs"].str.upper():
for state in states:
if state in suburb:
print(suburb, state)
结果是:
APOLLO BAY (TAS.) TAS
APOLLO BAY (VIC.) VIC
ACT REMAINDER - BELCONNI ACT
它跳过不匹配的那个。但是只要我添加一个额外的else
语句来打印not found
,结果将是全部not found
。有谁能帮我弄清楚这里出了什么问题,为什么?这相当令人沮丧,因为在我看来这是一个简单的任务。在
非常感谢你。在
目前没有回答
相关问题 更多 >
编程相关推荐