简体   繁体   中英

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

I want to add two new columns, one named 2016 and one named 2017. Then it should show the corresponding locations under the yrs. I have tried several ways like assign, insert, and with something like top2016['2016']=top2016['NAME'] but none worked. 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

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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