Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get the field name for data? #256

Open
jiaoL06 opened this issue Jun 2, 2023 · 1 comment
Open

How to get the field name for data? #256

jiaoL06 opened this issue Jun 2, 2023 · 1 comment
Labels

Comments

@jiaoL06
Copy link

jiaoL06 commented Jun 2, 2023

What's your question?

when I create the shapefile,such as:
w = shapefile.Writer(shapname)
w.field("name1", "C")
w.linez([data1])
w.record("cross1")
w.field("name2", "C")
w.linez([data2])
w.record("line1")
w.close()
Then I read the shapefile:
sf = shapefile.Reader(shapname)
datas = sf.shapes()
for data in datas:
points = data.points
x, y = zip(*points)
z = data.z

How to get the field name for data(x,y,z)?

@JamesParrott
Copy link
Collaborator

JamesParrott commented Sep 22, 2023

The field names are the same for all shapes. The name is the first item in the list for each field.

https://github.com/GeospatialPython/pyshp#reading-records

To see the fields for the Reader object above (sf) call the "fields" attribute:

>>> fields = sf.fields

e.g.:

[('DeletionFlag', 'C', 1, 0), ['name', 'C', 50, 0]]

To preserve the association between shapes and their records, I find it best to iterate over sf.shapeRecords()

https://github.com/GeospatialPython/pyshp#reading-geometry-and-records-simultaneously

This yields shapeRecords, which have a record attribute, which has a really nice ._as_dict method. The keys of the dictionary that returns are the field names.

with shapefile.Reader(shapname) as sf:
    for shaperec in sf.shapeRecords():
        points = shaperec.shape.points
        x, y = zip(*points)
        z = shaperec.shape.z   # I think, but haven't got a 3D shapefile right now to test this
        
        record_dict = sr.record.as_dict()

        fields = record_dict.keys()
        values = record_dict.values()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants