【问题标题】:How can I combine two csv files into one, by adding one column to the end of the first one?如何通过在第一个文件的末尾添加一列来将两个 csv 文件合并为一个文件?
【发布时间】:2014-10-06 00:13:18
【问题描述】:

我只需要将第二个 CSV 文件的列添加到第一个 CSV 文件中。

示例 CSV 文件 #1

Time Press RH Dewpt Alt

价值价值价值价值价值

对于 N 行。

示例 CSV 文件 #2

平滑温度

价值

我只是想成功

Time Press RH Dewpt Alt SmoothedTemperature

价值价值价值价值价值价值

还有一个有标题,另一个没有。

这是我目前所拥有的示例代码,但输出是文件 1 的最后一行,旁边是文件 #2 的完整数据集。

##specifying what they want to open
File = open(askopenfilename(), 'r')
##reading in the other file

Averaged = open('Moving_Average_Adjustment.csv','r')
##opening the new file via raw input to write to
filename = raw_input("Enter desired filename, EX: YYYYMMDD_SoundingNumber_Time.csv; must end in csv")
New_File = open(filename,'wb')



R = csv.reader(File, delimiter = ',')

## i feel the issue is here in my loop, i don't know how to print the first columns
## then also print the last column from the other CSV file on the end to make it mesh well

Write_New_File = csv.writer(New_File)
    data = ["Time,Press,Dewpt,RH,Alt,AveragedTemp"]
    Write_New_File.writerow(data)
    for i, line in enumerate(R):
        if i <=(header_count + MovingAvg/2):
            continue
    Time,Press,Temp,Dewpt,RH,Ucmp,Vcmp,spd,Dir,Wcmp,Lon,Lat,Ele,Azi,Alt,Qp,Qt,Qrh,Qu,Qv,QdZ=line
for i, line1 in enumerate(Averaged):
    if i == 1:
        continue
    SmoothedTemperature = line1
Calculated_Data = [Time,Press,Dewpt,RH,Alt,SmoothedTemperature]
Write_New_File.writerow(Calculated_Data)

【问题讨论】:

  • 对我有用的规则是“之前,把它放在屏幕上。如果你可以把想要的输出放在屏幕上,你可以把它放到一个文件中”

标签: python csv append


【解决方案1】:

如果你想走这条路,pandas 让 csv 操作变得非常容易。假设您的前两个示例表位于名为 test1.csvtest2.csv 的文件中:

>>> import pandas as pd
>>> test1 = pd.read_csv("test1.csv")
>>> test2 = pd.read_csv("test2.csv")
>>> test3 = pd.concat([test1, test2], axis=1)
>>> test3 
   Time   Press  RH   Dewpt  Alt  SmoothedTemperature
0      1      2    3      4    5                    6

[1 rows x 6 columns]

可以使用 DataFrame 方法 to_csv 将这个新表保存到 .csv 文件中。

如您所述,如果其中一个文件没有标题,您可以在读取文件时指定:

>>> test2 = pd.read_csv('test2.csv', header=None)

然后在pandas中手动更改标题行。

【讨论】:

  • 我不能使用熊猫。不幸的是,这段代码必须足够通用,以至于 6 所不同大学的不同人都可以使用它,而无需下载任何东西。
猜你喜欢
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多