Adding True or False to a new column based on for loop












1















I have a list of named polygons:



import pandas as pd
import geopandas as gp
df = gp.GeoDataFrame([['a',Polygon([(1, 0), (1, 1), (2,2), (1,2)])],
['b',Polygon([(1, 1), (2,2), (3,1)])]],
columns = ['name','geometry'])
df = gp.GeoDataFrame(df, geometry = 'geometry')


and a list of named points:



points = gp.GeoDataFrame( [['box', Point(1.5, 1.75)],
['cone', Point(3.0,2.0)],
['triangle', Point(2.5,1.25)]],
columns=['id', 'geometry'],
geometry='geometry')


Currently, I am running a for loop over these points and polygons to see which point falls within which polygon and returning there names and Ids to a list loc like so:



loc = 

for geo1, name in zip(df['geometry'], df['name']):
for geo2, id in zip(points['geometry'], points['id']):
if geo1.contains(geo2):
loc.append([id, name])


Now what I want to try and do is alter the loop so it adds a column to the points dataframe called 'inside' and returns 'True' if the point is in a polygon and 'False' if it isn't.



I've tried:



points['inside'] = ''
for geo1 in df['geometry']:
for geo2 in points['geometry']:
if geo1.contains(geo2):
points['inside'].append('True')


but it doesn't work



How can I best do this?



sorry if there is a very basic answer that I have missed.



Its been suggested below that this might be a duplicate of another question, however the one that is linked does not refer to adding the results to a column and whilst the Matplotlib methodology may be faster, when I run the example script provided I get the error float() argument must be a string or a number, not 'zip'










share|improve this question




















  • 1





    Possible duplicate of What's the fastest way of checking if a point is inside a polygon in python

    – Yuca
    Nov 21 '18 at 12:56











  • @Yuca I don't think this is a duplicate as that question doesn't relate to adding the results to a column in the dataframe. Also when I try the code for matplotlib I get an error: float() argument must be a string or a number, not 'zip'

    – tom91
    Nov 21 '18 at 13:09






  • 2





    Hi Tom, while the previous answer does not give you the answer in the format that you want/need, it does give you the answer for the bigger problem, which is 'the point is inside a polygon or not'. If you have an error implementing an approved answer then most likely thing is that you have a mistake

    – Yuca
    Nov 21 '18 at 13:12











  • Hi Yuca, I would like to try and make their solution work as it is meant to be faster, which is always useful, however I don't think their code works anymore as I copy and pasted the exact code to test it out.

    – tom91
    Nov 21 '18 at 13:19











  • just ran the code, works fine :) good luck

    – Yuca
    Nov 21 '18 at 13:22


















1















I have a list of named polygons:



import pandas as pd
import geopandas as gp
df = gp.GeoDataFrame([['a',Polygon([(1, 0), (1, 1), (2,2), (1,2)])],
['b',Polygon([(1, 1), (2,2), (3,1)])]],
columns = ['name','geometry'])
df = gp.GeoDataFrame(df, geometry = 'geometry')


and a list of named points:



points = gp.GeoDataFrame( [['box', Point(1.5, 1.75)],
['cone', Point(3.0,2.0)],
['triangle', Point(2.5,1.25)]],
columns=['id', 'geometry'],
geometry='geometry')


Currently, I am running a for loop over these points and polygons to see which point falls within which polygon and returning there names and Ids to a list loc like so:



loc = 

for geo1, name in zip(df['geometry'], df['name']):
for geo2, id in zip(points['geometry'], points['id']):
if geo1.contains(geo2):
loc.append([id, name])


Now what I want to try and do is alter the loop so it adds a column to the points dataframe called 'inside' and returns 'True' if the point is in a polygon and 'False' if it isn't.



I've tried:



points['inside'] = ''
for geo1 in df['geometry']:
for geo2 in points['geometry']:
if geo1.contains(geo2):
points['inside'].append('True')


but it doesn't work



How can I best do this?



sorry if there is a very basic answer that I have missed.



Its been suggested below that this might be a duplicate of another question, however the one that is linked does not refer to adding the results to a column and whilst the Matplotlib methodology may be faster, when I run the example script provided I get the error float() argument must be a string or a number, not 'zip'










share|improve this question




















  • 1





    Possible duplicate of What's the fastest way of checking if a point is inside a polygon in python

    – Yuca
    Nov 21 '18 at 12:56











  • @Yuca I don't think this is a duplicate as that question doesn't relate to adding the results to a column in the dataframe. Also when I try the code for matplotlib I get an error: float() argument must be a string or a number, not 'zip'

    – tom91
    Nov 21 '18 at 13:09






  • 2





    Hi Tom, while the previous answer does not give you the answer in the format that you want/need, it does give you the answer for the bigger problem, which is 'the point is inside a polygon or not'. If you have an error implementing an approved answer then most likely thing is that you have a mistake

    – Yuca
    Nov 21 '18 at 13:12











  • Hi Yuca, I would like to try and make their solution work as it is meant to be faster, which is always useful, however I don't think their code works anymore as I copy and pasted the exact code to test it out.

    – tom91
    Nov 21 '18 at 13:19











  • just ran the code, works fine :) good luck

    – Yuca
    Nov 21 '18 at 13:22
















1












1








1








I have a list of named polygons:



import pandas as pd
import geopandas as gp
df = gp.GeoDataFrame([['a',Polygon([(1, 0), (1, 1), (2,2), (1,2)])],
['b',Polygon([(1, 1), (2,2), (3,1)])]],
columns = ['name','geometry'])
df = gp.GeoDataFrame(df, geometry = 'geometry')


and a list of named points:



points = gp.GeoDataFrame( [['box', Point(1.5, 1.75)],
['cone', Point(3.0,2.0)],
['triangle', Point(2.5,1.25)]],
columns=['id', 'geometry'],
geometry='geometry')


Currently, I am running a for loop over these points and polygons to see which point falls within which polygon and returning there names and Ids to a list loc like so:



loc = 

for geo1, name in zip(df['geometry'], df['name']):
for geo2, id in zip(points['geometry'], points['id']):
if geo1.contains(geo2):
loc.append([id, name])


Now what I want to try and do is alter the loop so it adds a column to the points dataframe called 'inside' and returns 'True' if the point is in a polygon and 'False' if it isn't.



I've tried:



points['inside'] = ''
for geo1 in df['geometry']:
for geo2 in points['geometry']:
if geo1.contains(geo2):
points['inside'].append('True')


but it doesn't work



How can I best do this?



sorry if there is a very basic answer that I have missed.



Its been suggested below that this might be a duplicate of another question, however the one that is linked does not refer to adding the results to a column and whilst the Matplotlib methodology may be faster, when I run the example script provided I get the error float() argument must be a string or a number, not 'zip'










share|improve this question
















I have a list of named polygons:



import pandas as pd
import geopandas as gp
df = gp.GeoDataFrame([['a',Polygon([(1, 0), (1, 1), (2,2), (1,2)])],
['b',Polygon([(1, 1), (2,2), (3,1)])]],
columns = ['name','geometry'])
df = gp.GeoDataFrame(df, geometry = 'geometry')


and a list of named points:



points = gp.GeoDataFrame( [['box', Point(1.5, 1.75)],
['cone', Point(3.0,2.0)],
['triangle', Point(2.5,1.25)]],
columns=['id', 'geometry'],
geometry='geometry')


Currently, I am running a for loop over these points and polygons to see which point falls within which polygon and returning there names and Ids to a list loc like so:



loc = 

for geo1, name in zip(df['geometry'], df['name']):
for geo2, id in zip(points['geometry'], points['id']):
if geo1.contains(geo2):
loc.append([id, name])


Now what I want to try and do is alter the loop so it adds a column to the points dataframe called 'inside' and returns 'True' if the point is in a polygon and 'False' if it isn't.



I've tried:



points['inside'] = ''
for geo1 in df['geometry']:
for geo2 in points['geometry']:
if geo1.contains(geo2):
points['inside'].append('True')


but it doesn't work



How can I best do this?



sorry if there is a very basic answer that I have missed.



Its been suggested below that this might be a duplicate of another question, however the one that is linked does not refer to adding the results to a column and whilst the Matplotlib methodology may be faster, when I run the example script provided I get the error float() argument must be a string or a number, not 'zip'







python python-3.x pandas






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 13:12







tom91

















asked Nov 21 '18 at 12:31









tom91tom91

16111




16111








  • 1





    Possible duplicate of What's the fastest way of checking if a point is inside a polygon in python

    – Yuca
    Nov 21 '18 at 12:56











  • @Yuca I don't think this is a duplicate as that question doesn't relate to adding the results to a column in the dataframe. Also when I try the code for matplotlib I get an error: float() argument must be a string or a number, not 'zip'

    – tom91
    Nov 21 '18 at 13:09






  • 2





    Hi Tom, while the previous answer does not give you the answer in the format that you want/need, it does give you the answer for the bigger problem, which is 'the point is inside a polygon or not'. If you have an error implementing an approved answer then most likely thing is that you have a mistake

    – Yuca
    Nov 21 '18 at 13:12











  • Hi Yuca, I would like to try and make their solution work as it is meant to be faster, which is always useful, however I don't think their code works anymore as I copy and pasted the exact code to test it out.

    – tom91
    Nov 21 '18 at 13:19











  • just ran the code, works fine :) good luck

    – Yuca
    Nov 21 '18 at 13:22
















  • 1





    Possible duplicate of What's the fastest way of checking if a point is inside a polygon in python

    – Yuca
    Nov 21 '18 at 12:56











  • @Yuca I don't think this is a duplicate as that question doesn't relate to adding the results to a column in the dataframe. Also when I try the code for matplotlib I get an error: float() argument must be a string or a number, not 'zip'

    – tom91
    Nov 21 '18 at 13:09






  • 2





    Hi Tom, while the previous answer does not give you the answer in the format that you want/need, it does give you the answer for the bigger problem, which is 'the point is inside a polygon or not'. If you have an error implementing an approved answer then most likely thing is that you have a mistake

    – Yuca
    Nov 21 '18 at 13:12











  • Hi Yuca, I would like to try and make their solution work as it is meant to be faster, which is always useful, however I don't think their code works anymore as I copy and pasted the exact code to test it out.

    – tom91
    Nov 21 '18 at 13:19











  • just ran the code, works fine :) good luck

    – Yuca
    Nov 21 '18 at 13:22










1




1





Possible duplicate of What's the fastest way of checking if a point is inside a polygon in python

– Yuca
Nov 21 '18 at 12:56





Possible duplicate of What's the fastest way of checking if a point is inside a polygon in python

– Yuca
Nov 21 '18 at 12:56













@Yuca I don't think this is a duplicate as that question doesn't relate to adding the results to a column in the dataframe. Also when I try the code for matplotlib I get an error: float() argument must be a string or a number, not 'zip'

– tom91
Nov 21 '18 at 13:09





@Yuca I don't think this is a duplicate as that question doesn't relate to adding the results to a column in the dataframe. Also when I try the code for matplotlib I get an error: float() argument must be a string or a number, not 'zip'

– tom91
Nov 21 '18 at 13:09




2




2





Hi Tom, while the previous answer does not give you the answer in the format that you want/need, it does give you the answer for the bigger problem, which is 'the point is inside a polygon or not'. If you have an error implementing an approved answer then most likely thing is that you have a mistake

– Yuca
Nov 21 '18 at 13:12





Hi Tom, while the previous answer does not give you the answer in the format that you want/need, it does give you the answer for the bigger problem, which is 'the point is inside a polygon or not'. If you have an error implementing an approved answer then most likely thing is that you have a mistake

– Yuca
Nov 21 '18 at 13:12













Hi Yuca, I would like to try and make their solution work as it is meant to be faster, which is always useful, however I don't think their code works anymore as I copy and pasted the exact code to test it out.

– tom91
Nov 21 '18 at 13:19





Hi Yuca, I would like to try and make their solution work as it is meant to be faster, which is always useful, however I don't think their code works anymore as I copy and pasted the exact code to test it out.

– tom91
Nov 21 '18 at 13:19













just ran the code, works fine :) good luck

– Yuca
Nov 21 '18 at 13:22







just ran the code, works fine :) good luck

– Yuca
Nov 21 '18 at 13:22














1 Answer
1






active

oldest

votes


















1














You are trying to append to a string...



Just change the line points['inside'] = '' to points['inside'] =



points['inside'] = 
for geo1 in df['geometry']:
for geo2 in points['geometry']:
if geo1.contains(geo2):
points['inside'].append('True')


This works for me...



Hope you find this helpful!






share|improve this answer
























  • Hey that makes a lot of sense! however when I run this I get the error: 'Length of values does not match length of index'

    – tom91
    Nov 21 '18 at 12:54






  • 1





    @tom91 hi did you ever figure it out? do you still need help?

    – Moshe Slavin
    Dec 31 '18 at 13:35











  • Hi, I know why the error is occuring but I don't know how to fix it!

    – tom91
    Jan 10 at 11:06











  • Hi @tom91, can you show your new code? what is the error you are getting?

    – Moshe Slavin
    Jan 10 at 11:44











  • I've tried running the above code and the error is still 'Length of values does not match length of index'. This is because it returns three values whilst there are only two columns in points. How would I aggregate the output of the ablve for loop to produce counts of 'True', so the point that has 2 Trues is asigned a value of 2 and the point with 1 True is asigned a value of 1?

    – tom91
    Jan 10 at 11:49













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53412096%2fadding-true-or-false-to-a-new-column-based-on-for-loop%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














You are trying to append to a string...



Just change the line points['inside'] = '' to points['inside'] =



points['inside'] = 
for geo1 in df['geometry']:
for geo2 in points['geometry']:
if geo1.contains(geo2):
points['inside'].append('True')


This works for me...



Hope you find this helpful!






share|improve this answer
























  • Hey that makes a lot of sense! however when I run this I get the error: 'Length of values does not match length of index'

    – tom91
    Nov 21 '18 at 12:54






  • 1





    @tom91 hi did you ever figure it out? do you still need help?

    – Moshe Slavin
    Dec 31 '18 at 13:35











  • Hi, I know why the error is occuring but I don't know how to fix it!

    – tom91
    Jan 10 at 11:06











  • Hi @tom91, can you show your new code? what is the error you are getting?

    – Moshe Slavin
    Jan 10 at 11:44











  • I've tried running the above code and the error is still 'Length of values does not match length of index'. This is because it returns three values whilst there are only two columns in points. How would I aggregate the output of the ablve for loop to produce counts of 'True', so the point that has 2 Trues is asigned a value of 2 and the point with 1 True is asigned a value of 1?

    – tom91
    Jan 10 at 11:49


















1














You are trying to append to a string...



Just change the line points['inside'] = '' to points['inside'] =



points['inside'] = 
for geo1 in df['geometry']:
for geo2 in points['geometry']:
if geo1.contains(geo2):
points['inside'].append('True')


This works for me...



Hope you find this helpful!






share|improve this answer
























  • Hey that makes a lot of sense! however when I run this I get the error: 'Length of values does not match length of index'

    – tom91
    Nov 21 '18 at 12:54






  • 1





    @tom91 hi did you ever figure it out? do you still need help?

    – Moshe Slavin
    Dec 31 '18 at 13:35











  • Hi, I know why the error is occuring but I don't know how to fix it!

    – tom91
    Jan 10 at 11:06











  • Hi @tom91, can you show your new code? what is the error you are getting?

    – Moshe Slavin
    Jan 10 at 11:44











  • I've tried running the above code and the error is still 'Length of values does not match length of index'. This is because it returns three values whilst there are only two columns in points. How would I aggregate the output of the ablve for loop to produce counts of 'True', so the point that has 2 Trues is asigned a value of 2 and the point with 1 True is asigned a value of 1?

    – tom91
    Jan 10 at 11:49
















1












1








1







You are trying to append to a string...



Just change the line points['inside'] = '' to points['inside'] =



points['inside'] = 
for geo1 in df['geometry']:
for geo2 in points['geometry']:
if geo1.contains(geo2):
points['inside'].append('True')


This works for me...



Hope you find this helpful!






share|improve this answer













You are trying to append to a string...



Just change the line points['inside'] = '' to points['inside'] =



points['inside'] = 
for geo1 in df['geometry']:
for geo2 in points['geometry']:
if geo1.contains(geo2):
points['inside'].append('True')


This works for me...



Hope you find this helpful!







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 21 '18 at 12:41









Moshe SlavinMoshe Slavin

1,7182821




1,7182821













  • Hey that makes a lot of sense! however when I run this I get the error: 'Length of values does not match length of index'

    – tom91
    Nov 21 '18 at 12:54






  • 1





    @tom91 hi did you ever figure it out? do you still need help?

    – Moshe Slavin
    Dec 31 '18 at 13:35











  • Hi, I know why the error is occuring but I don't know how to fix it!

    – tom91
    Jan 10 at 11:06











  • Hi @tom91, can you show your new code? what is the error you are getting?

    – Moshe Slavin
    Jan 10 at 11:44











  • I've tried running the above code and the error is still 'Length of values does not match length of index'. This is because it returns three values whilst there are only two columns in points. How would I aggregate the output of the ablve for loop to produce counts of 'True', so the point that has 2 Trues is asigned a value of 2 and the point with 1 True is asigned a value of 1?

    – tom91
    Jan 10 at 11:49





















  • Hey that makes a lot of sense! however when I run this I get the error: 'Length of values does not match length of index'

    – tom91
    Nov 21 '18 at 12:54






  • 1





    @tom91 hi did you ever figure it out? do you still need help?

    – Moshe Slavin
    Dec 31 '18 at 13:35











  • Hi, I know why the error is occuring but I don't know how to fix it!

    – tom91
    Jan 10 at 11:06











  • Hi @tom91, can you show your new code? what is the error you are getting?

    – Moshe Slavin
    Jan 10 at 11:44











  • I've tried running the above code and the error is still 'Length of values does not match length of index'. This is because it returns three values whilst there are only two columns in points. How would I aggregate the output of the ablve for loop to produce counts of 'True', so the point that has 2 Trues is asigned a value of 2 and the point with 1 True is asigned a value of 1?

    – tom91
    Jan 10 at 11:49



















Hey that makes a lot of sense! however when I run this I get the error: 'Length of values does not match length of index'

– tom91
Nov 21 '18 at 12:54





Hey that makes a lot of sense! however when I run this I get the error: 'Length of values does not match length of index'

– tom91
Nov 21 '18 at 12:54




1




1





@tom91 hi did you ever figure it out? do you still need help?

– Moshe Slavin
Dec 31 '18 at 13:35





@tom91 hi did you ever figure it out? do you still need help?

– Moshe Slavin
Dec 31 '18 at 13:35













Hi, I know why the error is occuring but I don't know how to fix it!

– tom91
Jan 10 at 11:06





Hi, I know why the error is occuring but I don't know how to fix it!

– tom91
Jan 10 at 11:06













Hi @tom91, can you show your new code? what is the error you are getting?

– Moshe Slavin
Jan 10 at 11:44





Hi @tom91, can you show your new code? what is the error you are getting?

– Moshe Slavin
Jan 10 at 11:44













I've tried running the above code and the error is still 'Length of values does not match length of index'. This is because it returns three values whilst there are only two columns in points. How would I aggregate the output of the ablve for loop to produce counts of 'True', so the point that has 2 Trues is asigned a value of 2 and the point with 1 True is asigned a value of 1?

– tom91
Jan 10 at 11:49







I've tried running the above code and the error is still 'Length of values does not match length of index'. This is because it returns three values whilst there are only two columns in points. How would I aggregate the output of the ablve for loop to produce counts of 'True', so the point that has 2 Trues is asigned a value of 2 and the point with 1 True is asigned a value of 1?

– tom91
Jan 10 at 11:49




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53412096%2fadding-true-or-false-to-a-new-column-based-on-for-loop%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

"Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

Alcedinidae

RAC Tourist Trophy