简体   繁体   English

在运行时更改数据框的列名

[英]Change the column name of dataframe at runtime

I am trying to initialize an empty dataframe with 5 column values. 我正在尝试使用5列值初始化一个空的数据框。 Say column1, column2, column3, column4, column5. 说出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. 由于有5列,因此更容易单独进行。 But i have to extend the number of columns of the dataframe to 70. For that I am using for loop. 但是我必须将数据帧的列数扩展到70。为此,我正在使用for循环。

To update the coulmn value I was using dataframe['column "+count+"'] = .... where count is an incremental variable ranging upto 70. 为了更新库仑值,我使用了dataframe['column "+count+"'] = .... ,其中count是一个增量变量,范围最大为70。

But the above code adds a new column to the dataframe. 但是上面的代码在数据框中添加了一个新列。 How can I use the count variable to access these column names? 如何使用count变量访问这些列名?

i would recommend just using pandas.io.sql to download your database data. 我建议仅使用pandas.io.sql下载您的数据库数据。 it returns your data in a DataFrame . 它在DataFrame返回您的数据。

but if, for some reason, you want to access the columns, you already have your answer: 但是如果由于某种原因要访问这些列,则已经有了答案:

assignment: df['column%d' % count] = data 分配: df['column%d' % count] = data
retrieval: df['column%d' % count] 检索: df['column%d' % count]

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

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