Adding True or False to a new column based on for loop
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
|
show 2 more comments
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
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
|
show 2 more comments
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
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
python python-3.x pandas
edited Nov 21 '18 at 13:12
asked Nov 21 '18 at 12:31
tom91
859
859
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
|
show 2 more comments
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
|
show 2 more comments
1 Answer
1
active
oldest
votes
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!
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
@tom91 hi did you ever figure it out? do you still need help?
– Moshe Slavin
Dec 31 '18 at 13:35
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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!
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
@tom91 hi did you ever figure it out? do you still need help?
– Moshe Slavin
Dec 31 '18 at 13:35
add a comment |
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!
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
@tom91 hi did you ever figure it out? do you still need help?
– Moshe Slavin
Dec 31 '18 at 13:35
add a comment |
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!
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!
answered Nov 21 '18 at 12:41
Moshe Slavin
1,1691721
1,1691721
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
@tom91 hi did you ever figure it out? do you still need help?
– Moshe Slavin
Dec 31 '18 at 13:35
add a comment |
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
@tom91 hi did you ever figure it out? do you still need help?
– Moshe Slavin
Dec 31 '18 at 13:35
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
@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
add a comment |
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.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- 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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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