简体   繁体   English

在一个标题下按列附加到 csv 文件

[英]Append to csv file column-wise under one header

Coding in Python 2.7.在 Python 2.7 中编码。 I have a csv file already present called input.csv.我已经存在一个名为 input.csv 的 csv 文件。 In that file we have 3 headers — Filename, Category, Version — under which certain values already exist.在该文件中,我们有 3 个标题——文件名、类别、版本——在这些标题下已经存在某些值。

I want to know how I can reopen the csv file and input only one value multiple times under the "Version" column such that whatever was written under "Version" gets overwritten by the new input.我想知道如何重新打开 csv 文件并在“版本”列下多次输入一个值,这样在“版本”下写入的任何内容都会被新输入覆盖。

So suppose under the "Version" column I had 3 inputs in 3 rows:因此,假设在“版本”列下,我在 3 行中有 3 个输入:

VERSION
  55
  66
  88

It gets rewritten by my new input 10 so it will look like:它被我的新输入 10 重写,所以它看起来像:

VERSION
  10
  10
  10

I know normally we input csv row-wise but this time around I just want to input column wise under that specific header "Version".我知道通常我们按行输入 csv,但这次我只想在特定标题“版本”下按列输入。

Solution 1:解决方案1:

With pandas , you can use:使用pandas ,您可以使用:

import pandas as pd
df = pd.read_csv(file)
df['VERSION'] = 10
df.to_csv(file, index=False)

Solution 2: If there are multiple rows (and you only want first 3), then you can use:解决方案 2:如果有多行(并且您只想要前 3 行),那么您可以使用:

df.loc[df.index < 3, ['VERSION']] = 10   

instead of:代替:

df['VERSION'] = 10

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

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