1

我需要从包含 800 多个地区的数据框中创建一个 .kml 文件。这是我到目前为止所做的:

1) 使用 PANDAS 读取 .csv 文件(图 1)

2) 通过仅选择前 3 列(经度、纬度、高度)来创建一个新的数据框

3)从数据框中创建一个元组列表

4) 创建一个 .kml 文件并做一些样式(颜色)

只有当有 1 个区时,所有这些程序才能很好地工作。现在我需要做同样的事情,但有 800 多个地区。在图 2 中,显示了具有 2 个区(ACTONO 和 AILSACRAIGO)的示例。

将dataframe转换为元组列表时,如何让“python”知道有很多区?

我相信这些线路必须改进:

a)在这里我需要一个元组列表(每个区一个)

#Converting the dataframe to a list of tuples
tuples = [tuple(x) for x in df_modify.values]

b)在这里,每个元组的“outboundaryies”都必须改变

pol = kml.newpolygon(name= 'ACTONO', description= 'Acton County', 
outerboundaryis=tuples, extrude=extrude, altitudemode=altitudemode)

这是所有代码:

带有 1 个区的 .CSV 代码

import pandas
import simplekml

kml = simplekml.Kml()

#Using PANDAS to read .csv and chosing the first 3 columns
df = pandas.read_csv('C:\\Users\\disa_ONTshp.csv')
df_modify=df.iloc[:, [0,1,2]]

#Converting the dataframe to a list of tuples
tuples = [tuple(x) for x in df_modify.values]


#Creating a .kml file
extrude=1
altitudemode = simplekml.AltitudeMode.relativetoground
pol = kml.newpolygon(name= 'ACTONO', description= 'Acton County', 
outerboundaryis=tuples, extrude=extrude, altitudemode=altitudemode)

#Styling colors
pol.style.linestyle.color = simplekml.Color.green
pol.style.linestyle.width = 5
pol.style.polystyle.color = simplekml.Color.changealphaint(100, 
simplekml.Color.green)

#Saving
kml.save("Polygon Styling.kml")

图 1(1 区)

图。1

图2(2个区)

CSV 文件

4

1 回答 1

1

这就是答案。我需要的是一个数据框字典。

import pandas as pd
import simplekml
import pprint
import numpy as np


kml = simplekml.Kml()

###LOADING THE .csv FILE WITH ALL THE COORDINATES (USING QGIS)
df = pd.read_csv('C:\\Users\\file.csv')



###ADDING A COLUMN "altitude" WITH RANDOM VALUES FROM 200 TO 2000
df['altitude']=df.groupby('name').name.transform(lambda x: np.random.randint(200,2000))

###CALLING THE COLUMNS OF INTEREST
df=df[['longitude', 'latitude', 'altitude', 'name']]



###CREATING A DICTIONARY OF DATAFRAMES (ONE FOR EACH DISTRICT) 
dict_dataframes=dict(tuple(df.groupby('name')))


###CALLING EACH DATAFRAME FROM THE DICTIONARY
for name, df in dict_dataframes.items():


    ###CREATING A LIST OF TUPLES WITH THE COLUMNS OF THE DATAFRAME
    tuples = [tuple(x) for x in df.values]


    extrude=1
    altitudemode = simplekml.AltitudeMode.relativetoground

    pol = kml.newpolygon(name = name, description="District of " + name, outerboundaryis=tuples, extrude=extrude, altitudemode=altitudemode)
    pol.style.linestyle.color = simplekml.Color.honeydew
    pol.style.linestyle.width = 3
    pol.style.polystyle.color = simplekml.Color.changealphaint(100, simplekml.Color.navy)


###SAVING THE FILE    
kml.save('C:\\Users\\3d_file.kml')
于 2019-11-05T21:21:16.523 回答