简体   繁体   中英

Coordinates output to csv file python

I am currently working on a project where i need to collect coordinates and transfer that to a csv file. I am using the k-means algorithm to find the coordinates (the centroids of a larger coordinate collection). The output is a list with coordinates. At first I wanted to simply copy it to an excel file, but that did not work as well as i wanted it to be.

This is my code:

df = pd.read_excel("centroid coordinaten excel lijst.xlsx")
df.head(n=16)
plt.scatter(df.X,df.Y)


km = KMeans(n_clusters=200)
print(km)

y_predict = km.fit_predict(df[['X','Y']])

print(y_predict)

df['cluster'] = y_predict

kmc = km.cluster_centers_
print(kmc)

#The output kmc is the list with coordinates and it looks like this: 

[[ 4963621.73063468 52320928.30284858]
[ 4981357.33667335 52293627.08917835]
[ 4974134.37538941 52313274.21495327]
[ 4945992.84398977 52304446.43606138]
[ 4986701.53977273 52317701.43831169]
[ 4993362.9143898  52296985.49271403]
[ 4949408.06109325 52320541.97963558]
[ 4966756.82872596 52301871.5655048 ]
[ 4980845.77591313 52324669.94175716]
[ 4970904.14472671 52292401.47190146]]

Is there anybode who knows how to convert the 'kmc' output into a csv file.

Thanks in advance!

You can do something like:

with open(yourfile, "w") as f:
  for line in kmc:
    for data in line:
      f.write(data + ",")
    f.write("\n")

You could use the csv library as follows:

import csv

kmc = [
    [4963621.73063468,52320928.30284858],
    [4981357.33667335,52293627.08917835],
    [4974134.37538941,52313274.21495327],
    [4945992.84398977,52304446.43606138],
    [4986701.53977273,52317701.43831169],
    [4993362.9143898,52296985.49271403],
    [4949408.06109325,52320541.97963558],
    [4966756.82872596,52301871.5655048],
    [4980845.77591313,52324669.94175716],
    [4970904.14472671,52292401.47190146],
]

with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(['lat', 'long'])
    csv_output.writerows(kmc)

Giving you output.csv containing:

lat,long
4963621.73063468,52320928.30284858
4981357.33667335,52293627.08917835
4974134.37538941,52313274.21495327
4945992.84398977,52304446.43606138
4986701.53977273,52317701.43831169
4993362.9143898,52296985.49271403
4949408.06109325,52320541.97963558
4966756.82872596,52301871.5655048
4980845.77591313,52324669.94175716
4970904.14472671,52292401.47190146

I suggest you put a full path to your output file to ensure you have write permission. Or as suggested, use sudo . Alternatively, you could add the following to the top:

import os

os.chdir(os.path.dirname(os.path.abspath(__file__)))

This ensures the output will be in the same folder as your script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM