【问题标题】:Add a column to a csv file at specified index with different values将列添加到具有不同值的指定索引处的 csv 文件
【发布时间】:2019-06-04 06:26:14
【问题描述】:

我想在每次给定索引中添加一个具有不同值的列(该值是根据行的值计算的)。 这是我的 csv 样本:

org,repo_name,stars_count,fork_count,commit_count
freeCodeCamp,freeCodeCamp,303178,22005,23183,1703
vuejs,vue,140222,20150,3016,82
twbs,bootstrap,133730,65555,18714,46
...

到目前为止,我尝试了这里提供的答案:python pandas insert column

def func(f):
    files = f
    df = pd.read_csv(files)
    df = df.convert_objects(convert_numeric=True)
    df.insert(2, 'new', 1000)
    df.to_csv(files) 

我得到一个添加到索引 2 的行的结果,值为 1000。

,org,repo_name,new,stars_count,fork_count,commit_count
freeCodeCamp,freeCodeCamp,303178,1000,22005,23183,1703
vuejs,vue,140222,1000,20150,3016,82
twbs,bootstrap,133730,1000,65555,18714,46
...

如何修改它以便能够为每一行添加一个特定的值,而不是到处添加 1000?以及如何添加标题以便获得以下输出?请注意 score1... scoreN 是 int 变量,而不是字符串,您可以假设它们已经被计算过。

org,repo_name,score,new,stars_count,fork_count,commit_count
freeCodeCamp,freeCodeCamp,303178,score1,22005,23183,1703
vuejs,vue,140222,score2,20150,3016,82
twbs,bootstrap,133730,score3,65555,18714,46
...

谢谢。

【问题讨论】:

  • 您希望您的 csv 看起来如何?让我们了解更多。
  • @AmazingThingsAroundYou 嗨,我最后给出了我想要的输出(我的最后一个代码 sn-p)。你指的是这个吗?
  • df.insert(2,'new',['score{}'.format(i+1) for i in range(len(df))]) ?
  • @anky_91,嗨,我已经编辑了我的帖子,因为它似乎不够清楚。 score 不是字符串,而是每行不同的 int。
  • @SoyänChardon 你得分如何?

标签: python pandas csv


【解决方案1】:

你可以试试这样的:

len_df = len(df.index)+1
df["new"] = ["score"+str(i) for i in range(1,len_df)]

我希望这会对你有所帮助。 好的,这可能会有所帮助:

df["new"].values[2] = score_value

注意 score_value 是int

【讨论】:

  • 嗨,可能不清楚,但 score 不是字符串,它是每行都不同的 int 变量,所以很遗憾你的回答没有帮助。我已经编辑了我的帖子以避免误解。
  • @SoyänChardon 我希望现在我编辑的答案会对您有所帮助。
【解决方案2】:

Pandas 只在 csv 中插入一个新列几乎是矫枉过正:

with open('input.csv') as fdin, open('output.csv', 'w', newline='') as fdout:
    rd = csv.DictReader(fdin)
    fields = list(rd.fieldnames)
    fields.insert(2, 'new')
    wr = csv.DictWriter(fdout, fieldnames=fields)
    wr.writeheader()
    for row in rd:
        row['new'] = compute_val(row)    # or compute_val(*row)
        wr.writerow(row)

【讨论】:

  • 您好,感谢您的回答。不幸的是,它不起作用,因为它不是在索引 2 处插入一列并因此向右移动其他列,而是覆盖索引 2 处列的内容。输出是 freeCodeCamp,freeCodeCamp,0.0628325397113628,22015,23213,1670, 而不是 freeCodeCamp,freeCodeCamp,0.0628325397113628,303198,22015,23213,1670
  • @SoyänChardon:它在我的测试中有效。也许您应该使用fields = list(rd.fieldnames) 来确保获得真实的列表。我已经编辑了我的帖子。
  • @SergeBellesta 非常感谢,它现在完美运行!
猜你喜欢
  • 2015-08-12
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
相关资源
最近更新 更多