Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 迭代组的键并将数据写入文件_Python 3.x_Macos_Geopandas - Fatal编程技术网

Python 3.x 迭代组的键并将数据写入文件

Python 3.x 迭代组的键并将数据写入文件,python-3.x,macos,geopandas,Python 3.x,Macos,Geopandas,我完全是Python的初学者。我想在groupby命令之后迭代键,如: Groups = Country.groupby(['province_territory']).groups for c in Groups: Region = Country[Country['province_territory'] == c] print(c) 我没有采用以下方法: A = gp.GeoDataFrame(Country[Country['province_territory'] == 'A'])

我完全是Python的初学者。我想在groupby命令之后迭代键,如:

Groups = Country.groupby(['province_territory']).groups
for c in Groups: 
Region = Country[Country['province_territory'] == c]
print(c)
我没有采用以下方法:

A = gp.GeoDataFrame(Country[Country['province_territory'] == 'A'])
B = gp.GeoDataFrame(Country[Country['province_territory'] == 'B'])
C = gp.GeoDataFrame(Country[Country['province_territory'] == 'C'])
D = gp.GeoDataFrame(Country[Country['province_territory'] == 'D'])

A.to_file('DATA/A')
B.to_file('DATA/B')
C.to_file('DATA/C')
D.to_file('DATA/D')

Country是一个geojson数据文件。

您非常接近,只需迭代组,查询主数据帧即可获得每个省/地区的子集数据帧。在
DataFrame.query
子句中,
@
字符用于包含变量。由于您是一名初学者,还值得一提的是
f'DATA/{territory}
的功能,它是在python3.6及其他版本中进行字符串格式化的一种非常干净的方法。它将在字符串中的该位置插入变量territory的值

用于国家/地区中的地区。groupby(['省\地区])。组:
df=Country.query('province\u territory==@territory')
df.to_文件(f'DATA/{territory}')
顺便说一句,如果您只需要一组唯一的省域值,而groupby方法不提供任何内容,那么更简洁的版本可以是:

适用于国家['province\u territory']中的地区。唯一()
df=Country.query('province\u territory==@territory')
df.to_文件(f'DATA/{territory}')

非常感谢,它对我来说运行得很好,只是对代码做了一些调整。我仍然需要在geopandas Geodataframe:for territory in Country['province\u territory'].unique():df=gp.Geodataframe(Country.query('province\u territory==@territory'))df.to_文件(f'DATA/{territory})