【问题标题】:How to create a new dataframe with every iteration of for loop in Python如何在 Python 中的 for 循环的每次迭代中创建一个新的数据框
【发布时间】:2019-03-01 08:23:01
【问题描述】:

Click here to see image

#### 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))

enter image description here

#

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

在每次迭代时我都想创建一个新的数据框,如何?

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

有没有办法将所有数据帧水平连接为单个数据帧

14、15、16(从第一张纸开始)、14A、15A、16A(从第二张纸开始)、14B、15B、16B、(从第三张纸开始)作为 col1、col2、col3、col4…… ....................

感谢您的帮助

【问题讨论】:

  • 欢迎来到 SO。请校对您的问题并学习如何正确格式化(尤其是您的代码)。还请内联发布您的代码,切勿作为图像发布。谢谢!

标签: python pandas python-3.6


【解决方案1】:

您应该提出您的问题,以便其他人可以从该网站获得最大优势。

我会尝试为这个问题提出解决方案。

在每次迭代时我都想创建一个新的数据框,如何?

这个想法是将数据帧存储为字典的值。

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"

现在你有很多数据帧并且你想连接,使用pandas.concat()

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

【讨论】:

  • @user9023836,如果有帮助,我很高兴。您可以通过将复选标记变为绿色或投票来接受答案。 :D
猜你喜欢
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多