简体   繁体   English

如何基于 csv 文件中的另一列向现有 csv 文件添加新列

[英]How to add a new column to an existing csv file based on another column within the csv file

top2016 = mean2016.sort_values('Snow Mean', ascending=False).drop_duplicates(subset='NAME', keep='first').head(3)
top2016.to_csv('top3.csv')

top2017 = mean2017.sort_values('Snow Mean', ascending=False).drop_duplicates(subset='NAME', keep='first').head(3)
top2017.to_csv('top3.csv', mode='a', header=False)

This is my code right now and my csv looks like this这是我现在的代码,我的 csv 看起来像这样

I want to add two new columns, one named 2016 and one named 2017. Then it should show the corresponding locations under the yrs.我想添加两个新列,一个名为 2016,一个名为 2017。然后它应该显示 yrs 下的相应位置。 I have tried several ways like assign, insert, and with something like top2016['2016']=top2016['NAME'] but none worked.我尝试了几种方法,例如分配、插入和top2016['2016']=top2016['NAME']方法,但都没有奏效。 What's the best way to do it?最好的方法是什么? This is how I want my file to look这就是我希望我的文件看起来的样子在此处输入图像描述

Any help please!请提供任何帮助!

Edit:编辑: 在此处输入图像描述

This is a portion of my mean2016 data这是我的 mean2016 数据的一部分

This could works:这可能有效:

top2016 = mean2016.sort_values('Snow Mean', ascending=False).drop_duplicates(subset='NAME', keep='first').head(3)
top2016.loc[:, '2016'] = top2016['NAME']

top2017 = mean2017.sort_values('Snow Mean', ascending=False).drop_duplicates(subset='NAME', keep='first').head(3)
top2017.loc[:, '2017'] = top2017['NAME']

top3 = pd.concat([top2016, top2017]).reset_index(drop=True)
top3.to_csv('top3.csv')

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

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