[英]Pandas - Iterating over an index in a loop
I have a weird interaction that I would need help with.我有一个奇怪的互动需要帮助。 Basically :基本上 :
1) I have created a pandas dataframe that containts 1179 rows x 6 columns. 1)我创建了一个包含 1179 行 x 6 列的 Pandas 数据框。 One column is street names and the same value will have several duplicates (because each line represents a point, and each point is associated with a street).一列是街道名称,相同的值将有多个重复项(因为每条线代表一个点,而每个点都与一条街道相关联)。
2) I also have a list of all the streets in this panda dataframe. 2)我还有这个熊猫数据框中所有街道的列表。
3)If I run this line, I get an output of all the rows matching that street name: 3)如果我运行这一行,我会得到与该街道名称匹配的所有行的输出:
print(sub_df[sub_df.AQROUTES_3=='AvenueMermoz'])
Result :结果 :
FID AQROUTES_3 ... BEARING E_ID
983 983 AvenueMermoz ... 288.058014
984 984 AvenueMermoz ... 288.058014
992 992 AvenueMermoz ... 288.058014
1005 1005 AvenueMermoz ... 288.058014
1038 1038 AvenueMermoz ... 288.058014
1019 1019 AvenueMermoz ... 288.058014
However, if I run this command in a loop with the string of my list as the street name, it returns an empty dataframe :但是,如果我以我的列表字符串作为街道名称在循环中运行此命令,它将返回一个空数据框:
x=()
for names in pd_streetlist:
print(names)
x=names
print(sub_df[sub_df.AQROUTES_3 =="'"+str(x)+"'"])
x=()
Returns :回报:
RangSaint_Joseph
Empty DataFrame
Columns: [FID, AQROUTES_3, X, Y, BEARING, E_ID]
Index: []
AvenueAugustin
Empty DataFrame
Columns: [FID, AQROUTES_3, X, Y, BEARING, E_ID]
Index: []
and so on...等等...
I can't figure out why.我不明白为什么。 Anybody has an idea?有人有想法吗?
Thanks谢谢
I believe the issue is in this line:我相信问题出在这一行:
print(sub_df[sub_df.AQROUTES_3 =="'"+str(x)+"'"])
To each names
you add unnecessarily quote characters at the beginning and at the end so that each valid name of the street (in your example 'AvenueMermoz'
turns into "'AvenueMermoz'"
where we had to use double quotes to enclose single-quoted string).对于每个names
您在开头和结尾添加不必要的引号字符,以便街道的每个有效名称(在您的示例中'AvenueMermoz'
变成"'AvenueMermoz'"
,我们必须使用双引号将单引号字符串括起来)。
As @busybear has commented - there is no need to cast to str
either.正如@busybear 所评论的那样 - 也不需要强制转换为str
。 So, the corrected line would be:因此,更正后的行将是:
print(sub_df[sub_df.AQROUTES_3 == x])
So youre adding quotation marks to the filter which you shouldnt.因此,您向过滤器添加了不应该使用的引号。 now youre filtering on 'AvenueMermoz' while you just want to filter on AvenueMermoz .现在您正在过滤 'AvenueMermoz' 而您只想过滤 AvenueMermoz 。
so所以
print(sub_df[sub_df.AQROUTES_3 =="'"+str(x)+"'"])
should become应该成为
print(sub_df[sub_df.AQROUTES_3 ==str(x)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.