import geopandas as gpd
from sqlalchemy import create_engine
gdf = gpd.read_file("E:/data/test/HQ_JD.shp")
engine = create_engine("postgresql://your_username:your_password@localhost:5432/your_database")
gdf.to_postgis("HQ_JD", engine, if_exists="replace")
1.批量入库
import os
import geopandas as gpd
from sqlalchemy import create_engine
engine = create_engine("postgresql://your_username:your_password@localhost:5432/your_database")
folder_path = "E:/data"
for filename in os.listdir(folder_path):
if filename.endswith(".geojson"):
file_path = os.path.join(folder_path, filename)
gdf = gpd.read_file(file_path)
table_name = os.path.splitext(filename)[0]
gdf.to_postgis(table_name, engine, if_exists="replace")
2.shp入库会因为编码格式为乱码
import os
import geopandas as gpd
from sqlalchemy import create_engine
engine = create_engine("postgresql://postgres:wkun139@localhost:5432/postgres")
folder_path = "E:/data/test"
for filename in os.listdir(folder_path):
if filename.endswith(".geojson"):
file_path = os.path.join(folder_path, filename)
try:
gdf = gpd.read_file(file_path, encoding='GBK')
except UnicodeDecodeError:
gdf = gpd.read_file(file_path, encoding='UTF-8', errors='ignore')
table_name = os.path.splitext(filename)[0]
gdf.to_postgis(table_name, engine, if_exists="replace")
print("运行完毕!!!")
3.json嵌套多层格式错误解决
"""
这通常发生在将含有嵌套结构的 JSON 数据导入到 PostgreSQL 数据库时。在这种情况下,GeoPandas 可能无法正确处理 JSON 字段,导致数据格式发生变化。
要解决这个问题,可以在将数据导入到 PostgreSQL 之前,对含有 JSON 的列进行适当的处理。可以使用 Python 的 json 库来确保 JSON 数据以正确的格式存储。
以下是修改后的代码示例:
"""
import geopandas as gpd
from sqlalchemy import create_engine
import json
import os
def import_file_to_postgis(file_path, db_url, table_name):
gdf = gpd.read_file(file_path)
if os.path.splitext(file_path)[1].lower() in ['.json', '.geojson']:
json_columns = ['style', 'options']
existing_json_columns = [col for col in json_columns if col in gdf.columns]
for col in existing_json_columns:
gdf[col] = gdf[col].apply(json.dumps)
engine = create_engine(db_url)
gdf.to_postgis(table_name, engine, if_exists="replace")
shapefile_path = "E:/data/test/ce/python.json"
db_url = "postgresql://postgres:wkun139@localhost:5432/postgres"
table_name = "python"
import_file_to_postgis(shapefile_path, db_url, table_name)
"""
这里的关键步骤是使用 json.dumps 函数将 python 对象转换 为 JSON字符串。这样,在导入到数据库时,JSON 数据将被正确地作为字符串处理,从而避免了格式上的改变。
替换 'json_column' 为数据帧中实际包含 JSON 数据的列的名称。如果有多个这样的列,你需要对每个列重复这个处理过程。
"""
- 参考
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/e93ca4e53f3f4007989dbba6b3418c47.png)