代码之家  ›  专栏  ›  技术社区  ›  Nic

在python中使用x和y值从两个csv文件创建单个csv

  •  1
  • Nic  · 技术社区  · 6 年前

    我正在尝试创建一个具有所有可能组合的csv(例如x1、y1;x1、y2;x1、y3;x2、y1;x2、y2;x2、y3…)。等)

    import csv
    
    inLatCSV = r"C:\data\Lat.csv"
    inLongCSV = r"C:\data\Long.csv"
    outCSV = r"C:\data\LatLong.csv"
    
    with open(inLatCSV, 'r') as f:
      reader = csv.reader(f)
      list_Lat = list(reader)
    
    with open(inLongCSV, 'r') as f:
       reader = csv.reader(f)
       list_Long = list(reader)
    
    with open(outCSV, 'w') as myfile:
       for y in list_Lat:
           for x in list_Long:
                combVal = (y,x)
                #print (combVal)
                wr = csv.writer(myfile)
                wr.writerow(combVal)
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Uncle Ben Ben    6 年前

    open

    with open(my_csv, 'w', newline="") as myfile:
        combinations = [[y,x] for y in list_Lat for x in list_Long]
        wr = csv.writer(myfile)
        wr.writerows(combinations)
    
        2
  •  1
  •   dashiell    6 年前

    Pandas

    import pandas as pd
    
    lats = pd.read_csv("C:\data\Lat.csv",header=None)
    lons = pd.read_csv("C:\data\Long.csv",header=None)
    
    lats['_tmp'] = 1
    lons['_tmp'] = 1
    
    df = pd.merge(lats,lons,on='_tmp').drop('_tmp',axis=1)
    df.to_csv('C:\data\LatLong.csv',header=False,index=False)
    

    https://pandas.pydata.org/pandas-docs/version/0.20/merging.html