简体   繁体   中英

Python + Pandas + Dataframe : Generating dynamic column name for Pandas dataframe column

data['Predicted Order'] = predicted_order
print(data)
data.to_csv('smallys_ARMA.csv', encoding='utf-8', index=False)

The Pandas dataframe data gets a new column Predicted Order in the dataframe whose values are assigned to the list predicted_order .

Here, I don't want to hard code the newly generated column name, now it's Predicted Order . I want every newly generated column takes name dynamically like this Week_i for i = 0,1,2 etc.

Edit: This code will be run unknown number of times in future and each time it will add a new column to the dataframe.

maybe a thing like that:

numbers = range(52)
for i in numbers:
    if not "weeks_{i}" in df.columns:
        df["weeks_{i}"] = predicted_order
        break

You can use string formatting for that.

weeks = range(42)

for i in weeks:
     data[f'Week_{i}'] = predicted_order

If you are using Python < 3.6 then use data['Week_{}'.format(i)] instead

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