如何在Python中的for循环的每次迭代中创建一个新的数据框 [英] How to create a new dataframe with every iteration of for loop in Python

查看:391
本文介绍了如何在Python中的for循环的每次迭代中创建一个新的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击此处查看图片

#### the data is inverted #######

#### To bring back to its original position ####### 
   df_1= df_i.iloc[::-1]

#### Set index again ###################
df_1.index = range(len(df_1.index))

在此处输入图片描述

因为我正在创建数据帧df,但是我希望数据帧名称为df_0,df_1,df_2 ........................... .. df_n

In for I am creating a data frame df , But I want the data frame name as df_0, df_1, df_2 .......................... df_n

在每次迭代中,我都想创建一个新的数据框,怎么做?

On every iteration I want create a new data frame, How?

我的计数= 22,这意味着我的循环将运行22次.

And my count = 22, That means my loop will run for 22 times.

有没有一种方法可以将所有数据帧水平合并为单个dta帧

Is there a way that I concat horizontally all the data frames as a single dta frame

14、15、16(来自第一页),14A,15A,16A(来自第二页),14B,15B,16B(来自第三页)作为col1,col2,col3,col4 ...... .................

14, 15, 16 (from first sheet), 14A, 15A, 16A (from second Sheet), 14B,15B, 16B,(From Third sheet) as col1, col2, col3,col4.......................

感谢您的帮助

推荐答案

您应该提出问题,以便其他人从此站点中获得最大的利益.

You should make up your question so that other people will get max advantage from this site.

我将尝试为这个问题提出解决方案.

I will try to propose solution to this question.

在每次迭代中,我都想创建一个新的数据框,怎么做?

On every iteration I want create a new data frame, How?

想法是将数据帧存储为字典的值.

The idea is to store the dataframes as values of a dictionary.

cnt = 22  # your loop
dict_of_df = {} # initialize empty dictionary

for i in range(0,22):
    newname = df_sheetnames['col'].values[i]
    dict_of_df["df_{}".format(i)] = pd.read_excel('DATA.xlsx', sheetname=newname, skiprows=6, usecols=[14,15,16])

您可以通过调用dict_of_df[key]来访问数据帧,其中key = "df_1", "df_2", ... , "df_22"

You can access the dataframes by call dict_of_df[key], where key = "df_1", "df_2", ... , "df_22"

现在您有许多数据框,并且想要合并,请使用pandas.concat()

Now you have many dataframes and you want to concat, use pandas.concat()

如果您想在此之后重命名列, 只需写complete_df.columns = ['col1', 'col2', 'col3', ...]

If you want to rename the columns after that, simply write complete_df.columns = ['col1', 'col2', 'col3', ...]

这篇关于如何在Python中的for循环的每次迭代中创建一个新的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆