简体   繁体   中英

Change column names in pandas dataframe

I'm completely new to coding and learning on the go and need some advice.

I have a dataset imported into jupyter notebook from an excel.csv file. The column headers are all dates in the format "1/22/20" (22nd January 2020) and I want them to read as "Day1", "Day2", "Day3" etc. I have changed them manually to read as I want them but the csv file updates with a new column every day, which means that when I read it into my notebook to produce the graphs I want I first have to update the code in my notebook and add the extra "Dayxxx". This isn't a major problem but I have now 92 days in the csv file/dataset and it's getting boring. I wondered if there is a way to automatically add the "Dayxxx" by reading the file and with a for or while loop to change the column headers.

Any advice gratefully recieved, thanks.

Steptho.

I understand that those are your only columns and they are already ordered from first to last day? You can obtain the number of days by getting the length of the list of column names returned by df.columns. From there you can create a new list with the column names you desire.

import pandas as pd

df = pd.read_csv("your_csv")

no_columns = len(df.columns)
new_column_names = [] 
for day in range(no_columns):
    new_column_names.append("Day "+str(day+1))

df.columns = new_column_names

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