简体   繁体   English

如何使用python将某些csv文件列复制到另一个csv文件中?

[英]how to copy some csv file colums into another csv file with python?

I have a 10 columns csv file and i would like to copy the first, the third and the seventh or another set of columns into a new csv file. 我有一个10列的csv文件,我想将第一,第三和第七个或另一组列复制到一个新的csv文件中。 Can you help me? 你能帮助我吗? I have this code but i can't transform it to have my need. 我有这段代码,但是我无法将其转换为我的需要。

<code>
def selection( fr=sys.stdin, fw=sys.stdout, delim=';'):
    my_reader = csv.reader(fr, delimiter=delim)
    my_writer = csv.writer(fw, delimiter=delim)
    to_write = [ col for col in zip(*my_reader) if col[0] == 'Nb_doc' ]
    my_writer.writerows(zip(*to_write))
    return
</code>

this code copy only the column named 'nb_doc'. 此代码仅复制名为“ nb_doc”的列。

Maybe you could have a list of field names you'd like to select from and check if the first element of the column is in there: 也许您可以从中选择一个字段名称列表,然后检查该列的第一个元素是否在其中:

fields = ["Nb_doc", "SomeOtherField1", "SomeOtherField2"]

Then, your list comprehension probably just needs to look like this: 然后,您的列表理解可能只需要看起来像这样:

to_write = [ col for col in zip(*my_reader) if col[0] in fields ]

The following will copy just the first, third, and seventh columns: 下面将仅复制第一,第三和第七列:

colNums = [0, 2, 6]
to_write = [ col for i, col in enumerate(zip(*my_reader)) if i in colNums ]

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

相关问题 使用 python 将列从一个 csv 复制并附加到另一个 csv 文件 - Copy and append colums from one csv to another csv file using python 如何使用python将行排列到csv文件的列中? - How to arrange lines into colums of csv file with python? 使用 python 计算 csv 文件中的列 - counting colums in csv file with python 在某些情况下,如何将具有50000行和标题的CSV文件复制到另一个CSV文件? - How to copy CSV file with 50000 rows and a header to another CSV,with some conditions? 如何使用python将.csv文件中的一行复制到另一行 - How to copy one row in a .csv file to another row with python 如何在csv文件的不同列中打印输出? - How to print the output in different colums of a csv file? 如何将列从一个 csv 文件复制到另一个 csv 文件? - How to copy columns from one csv file to another csv file? Python 3,将特定列从一个csv文件复制到另一个csv - Python 3, Copy specific column from one csv file to another csv 如何使用 Python 和 Z251D1BBFE9A3B678CEAZ30DC 将 csv 文件中一个单元格的值复制到另一个 csv 文件? - How can I copy the value of one cell in a csv file to another csv file using Python and Pandas? 如何从 csv 文件中提取行并将其复制到 python 中的另一个 csv 文件? - How to extract and copy lines from csv file to another csv file in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM