用多个变量编写CSV

时间:2016-03-27 20:52:00

标签: python csv

我目前有两个列表:

lat = [34.78, 34.82, 34.86, 34.92]
lon = [-86.02, -86.06, -86.10, -86.14]

我正在尝试编写一个csv文件,将它们输出为lat / lon:

34.78, -86.02
34.82, -86.06
34.86, -86.10
34.92, -86.14

我尝试使用:

with open('lat_lon', 'w') as csvfile:
    writer=csv.writer(csvfile, delimiter=',')
    writer.writerow(lat)
    writer.writerow(lon)

但是这给了我一行中的lat值和一个单独行中的lon值。有关如何纠正此问题的任何想法?谢谢!

4 个答案:

答案 0 :(得分:3)

您只需要zip并使用 writerows 而不是writerow:

with open('lat_lon', 'w') as csvfile:
    writer=csv.writer(csvfile, delimiter=',')
    writer.writerows(zip(lat, lon))

答案 1 :(得分:2)

你几乎就在那里,做到这一点:

with open('lat_lon', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    for la, lo in zip(lat, lon):
        writer.writerow([la, lo])

或者更简洁(如上所述):

with open('lat_lon', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    writer.writerows(zip(lat, lon))

答案 2 :(得分:1)

import pandas as pd
lat = [34.78, 34.82, 34.86, 34.92]
lon = [-86.02, -86.06, -86.10, -86.14]

output = pd.DataFrame(lat, columns=['lat'])
output['lon'] = lon
output.to_csv('lat_lon', index=False)

答案 3 :(得分:0)

关键点是zip(lat,lon)。您可以使上述答案更加紧凑。

.box {
  display: block;
  width: 100%;
  text-align: center;
  margin: 0 auto;
}
.thumbnail {  
  height: 278px;
}
.box div.A, .box div.B, .box div.C, .box div.D  {
  float: left;
}

@media (max-width: 519px) {

.box div.A, .box div.B, .box div.C, .box div.D  {
  width: 100%;
}
}
@media (min-width: 520px) {

.box div.A, .box div.B, .box div.C, .box div.D  {
  width: 50%;
}
}
@media (min-width: 820px) {

.box div.A, .box div.B, .box div.C, .box div.D  {
  width: 25%;
}
}