简体   繁体   English

在现有的CSV中添加第三列

[英]Add a third column to existing CSV

I have a CSV file with 2 Columns (x,y) and 5653 rows formated like this 我有一个具有2列(x,y)和5653行格式的CSV文件

0,0
1,0
2,0
3,0
4,0
5,0
....
102,0
102,1
101,1
....
0,1
0,2
1,2
....

Now I want to add a third column to it out of another csv with meassured values eg -89 etc those are mean values. 现在,我想从另一个具有确定值(例如-89等)的csv中向其添加第三列。 these are also 5653 rows and its the first column of that file? 这些也是5653行,该文件的第一列? Now how can I read the first file read the second file and put it like this 现在我该如何读取第一个文件,再读取第二个文件,并像这样放置

0,0,-89
1,0,-89
2,0,-89
3,0,-89
4,0,-90
5,0,-90
6,0,-89
7,0,-89
8,0,-89
9,0,-89

So I want the values to be the same just in one CSV 所以我希望这些值在一个CSV中是相同的

You can use the csv module which unlike pandas does not require you to install any third-party libraries. 您可以使用csv模块,该模块与pandas不同,它不需要您安装任何第三方库。 You can just zip the two readers: 您可以zip两个阅读器:

import csv

with open('in1.csv') as fin1:
    with open('in2.csv') as fin2:
        with open('out.csv') as fout:
            r1 = csv.reader(fin1)  # iterator over lists of strings
            r2 = csv.reader(fin2)
            w = csv.reader(fout)
            for row1, row2 in zip(r1, r2):
                w.writerow(row1 + row2[:1])  # row from 1 + first column from 2

You could use the library pandas which is build to work with tabular data. 您可以使用为处理表格数据而构建的熊猫库。 typical workflow: 典型的工作流程:

import pandas as pd
df1 = pd.read_csv("your_path") # df is a shorthand for dataframe, a name for tabular data.

df2 = pd.read_csv("csv2")

# concanating: http://pandas.pydata.org/pandas-docs/stable/merging.html
result = pd.concat([df1, df2], axis=1) # join by row, not by column
result.to_csv("path")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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