简体   繁体   English

取 CSV 的第一行并将其转换为新列中的默认值

[英]Take 1st row of CSV and turn it into a default value in a new column

I have a fussy file export that basically creates a CSV with an odd format like:我有一个繁琐的文件导出,它基本上创建了一个带有奇怪格式的 CSV,例如:

filename, date
header1, header2, header3, header4
value1, value2, value3, value4
value5, value6, value7, value8

I'm trying to take that 'date' field from the first row and create a 5th column with that value as the default value.我正在尝试从第一行中获取该“日期”字段,并以该值作为默认值创建第 5 列。

I then want to delete that first row entirely.然后我想完全删除第一行。 Deleting the row isn't the issue, I just can't think of a way of selecting that date value and turning it into a new column.删除行不是问题,我只是想不出一种选择该日期值并将其转换为新列的方法。

You'll use the csv library to read like so:您将使用 csv 库读取如下内容:

import csv

with open('path_to_file_', 'r') as fh:
    reader = csv.reader(fh)

    # first get the date
    first_line = next(reader)
    date = first_line[1]

    # read the rest and add the date to every line
    lines = [l.append(date) for l in list(reader)]

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

相关问题 如果第一列值相同,MatLab(或任何其他语言)转换矩阵或csv以将第二列值放到同一行? - MatLab (or any other language) to convert a matrix or a csv to put 2nd column values to the same row if 1st column value is the same? 提取 HTML 表数据从 email 到 csv 文件,第一列值到行标题,使用 ZA7F5F35426B928727111 - Extracting HTML table data from email to csv file, 1st column values to row headers, using Python 根据Colum内值的第一次出现读取CSV文件的特定行 - Reading a Specific Row of a CSV File based on the 1st Occurrence of a value within a Colum 连接Python中具有相同第一列值的CSV文件的所有行 - Joining all rows of a CSV file that have the same 1st column value in Python 过滤pandas行,其中列中的第一个字母是/不是某个值 - Filter pandas row where 1st letter in a column is/is-not a certain value Python:将CSV列转换为数组,第一行和最后一行除外 - Python: convert CSV columns into arrays, except 1st and last row Python创建表并另存为CSV并显示第一行内容 - Python Create Tables and save as CSV and show 1st row contents 如何在第一行第一列输入 NaN 值? - How do you input NaN valiues in 1st row 1st column? 在Python上的.csv文件上获取第一列值 - Get 1st column values on .csv file on python 如何从csv中读取第一列并分离成多维数组 - How to read 1st column from csv and separate into multidimensional array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM