【发布时间】: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 你得分如何?