简体   繁体   English

使用来自另一个csv文件的列创建一个新的csv文件

[英]Create a new csv file with a column from another csv file

I am trying to create a new csv file with only one column from another exsting csv file. 我正在尝试使用另一个现有的csv文件中的仅一列创建一个新的csv文件。 Instead of printing Address in just one column in the csv file, Python is spreading the Address across multiple columns. Python不会在csv文件的仅一列中打印地址,而是将Address分布在多列中。 What can I do to eradicate the multiple column issue. 我该怎么办才能消除多列问题。

from __future__ import absolute_import, division, print_function
import csv
from itertools import imap
from operator import itemgetter


def main():
    delimiter = ','
    with open('C:/Addresses.csv', 'rb') as input_file:
        reader = csv.reader(input_file, delimiter=delimiter)
        with open('thefirstcolumn.csv', 'wb') as output_file:
            writer = csv.writer(output_file, delimiter=delimiter)
            writer.writerows(imap(itemgetter(1), reader))


if __name__ == '__main__':
    main()

In the original file: 在原始文件中:

abcdcolumn      Address             
********-A-1    6525 Mountain   
********-A-2    6543 Mountain       
********-A-4    6579 Mountain   
********-A-5    6597 Mountain   
********-A-6    6615 Mountain       
********-A-7    6633 Mountain   

The Result in the new csv file: 新的csv文件中的结果:

    A   d   d   r   e   s   s           
    6   5   2   5       M   o   u   n   t
    6   5   4   3       M   o   u   n   t
    6   5   6   1       M   o   u   n   t
    6   5   7   9       M   o   u   n   t
    6   5   9   7       M   o   u   n   t
    6   6   1   5       M   o   u   n   t
    6   6   3   3       M   o   u   n   t

writer.writerows expects a list of lists, you are feeding it a list of strings. writer.writerows需要一个列表列表,您正在向它提供一个字符串列表。

Changing writer.writerows(imap(itemgetter(1), reader)) to something like: writer.writerows(imap(itemgetter(1), reader))更改为以下内容:

for address in imap(itemgetter(1), reader):
      writer.writerow([address])

should work. 应该管用。

In general I'd use the pandas package for csv file manipulation. 通常,我会使用pandas包进行csv文件操作。

import pandas
df = pandas.read_csv(input_file, delimiter=delimiter)
df['Address'].to_csv(output_file)

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

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