简体   繁体   中英

Change the column name of dataframe at runtime

I am trying to initialize an empty dataframe with 5 column values. Say column1, column2, column3, column4, column5.

Now I want to read data from database and want to insert specific column values from the database to this dataframe. Since there are 5 columns its easier to do it individually. But i have to extend the number of columns of the dataframe to 70. For that I am using for loop.

To update the coulmn value I was using dataframe['column "+count+"'] = .... where count is an incremental variable ranging upto 70.

But the above code adds a new column to the dataframe. How can I use the count variable to access these column names?

i would recommend just using pandas.io.sql to download your database data. it returns your data in a DataFrame .

but if, for some reason, you want to access the columns, you already have your answer:

assignment: df['column%d' % count] = data
retrieval: df['column%d' % count]

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