如何将两个csv文件合并为一个,方法是在第一个csv文件的末尾添加一个列?

2024-10-03 11:12:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

示例CSV文件#1

Time Press RH Dewpt Alt

Value Value Value Value Value

N行数。在

示例CSV文件#2

SmoothedTemperature

Value

我只想成功

Time Press RH Dewpt Alt SmoothedTemperature

Value Value Value Value Value Value

其中一个有标题,另一个没有。在

这里是我目前为止的示例代码,但是输出是重复的文件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)

Tags: 文件csvthetoinnewtimevalue
1条回答
网友
1楼 · 发布于 2024-10-03 11:12:45

如果你想走这条路,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文件中。在

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

^{pr2}$

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

相关问题 更多 >