【问题标题】:Resetting Pandas dataframe in iterable loop resulting in ValueError在可迭代循环中重置 Pandas 数据框导致 ValueError
【发布时间】:2021-01-25 22:31:02
【问题描述】:

我需要在 for 循环中重置 pandas 数据框的帮助。这是我当前逻辑的伪代码-

import pandas as pd
df_out = pd.DataFrame(columns = ['col1','col2','col3','col4'])

for filename in os.listdir(directory):

    #some logic that results in dataset stored in a list called - output

    #output stored in dataframe
    df = pd.DataFrame(output, columns = ['col1','col2'])

    #some other logic that is used to get col3 using list called - col3_output
    df.loc[:,'col3'] = col3_output

    #some other logic that is used to get col4 using list called - col4_output
    df.loc[:,'col4'] = col4_output

    #note - col3 and col4 output cannot be derived from existing columns i.e. col1, col2

    #reset the lists to empty for next iteration of file
    col3_output = []
    col4_output = []

    #assign output to df_out
    df_out = df_out.append(df)

    #######################################
    ## ERORR OCCURING HERE
    #######################################
    #resetting dataframe or deleting data
    del df

#write final df_out to file
#some logic

我尝试使用 df.iloc[0:0] 重置数据框并删除我正在创建的新列,但无济于事。我得到了错误 -

ValueError:使用可迭代设置时必须具有相等的 len 键和值

【问题讨论】:

  • 我的猜测是分配是通过引用完成的。尝试在循环开始时重置两个列表?
  • 谢谢@crissal。这将导致 'df' not defined 错误,因为在第一个循环中不会创建变量。
  • 您可以在 for 循环之外定义 cols_x_output,然后将它们设置为空列表作为 for 内的第一行,然后执行其余代码
  • 我明白你在说什么。然而,问题在于为我使用不同逻辑派生的每次迭代创建新列“col3”、“col4”。这就是为什么我需要删除数据框然后重新创建它。

标签: python pandas dataframe


【解决方案1】:

如果我理解正确,您只需要一个空数据框? 如果是这样df = pd.DataFrame() 只会覆盖旧的并制作一个空的df。

【讨论】:

  • 当我尝试时出现以下错误 - AttributeError: 'DataFrame' object has no attribute 'DataFrame'。
  • df = pd.DataFrame(columns= ['col1', 'col2', 'col3']) print(df) df = pd.DataFrame() print(df) 对不起,我是新手溢出,所以我不知道如何在评论中整齐地插入代码。但是当我输入上面的代码时,它会打印一个空数据框
  • 对不起,没用。我收到与我上面发布的相同的错误。感谢您的回复。
  • 嗯,很奇怪。我自己试了一下,这段代码返回一个空的数据框,你用的是什么版本的熊猫? test = {'test': [1, 2, 3, 4, 2, 6], 'test1': [43, 43, 34, 23, 43, 23], 'test3': [3, 2, 4, 3, 5, 5]} df = pd.DataFrame(test) print(df) df = pd.DataFrame(None) print(df)
  • 感谢@warmupp 的投入。如下所述的错误位于完全不同的代码段。我能够修复它。
【解决方案2】:

通过这次错误调试,我学到了一个艰难而成功的教训。经过进一步调查,我意识到该错误绝对不是由于无法删除或清空数据框 df。他们俩都在工作。

在获取 col3_output 列表的逻辑过程中发生了错误。我没有将其重置为空白以进行进一步的迭代(在示例示例中我做了但不是在原始示例中)。我应该说明的另一件事是引发错误的行号。

对于遇到类似错误的任何人,请检查以确保用于添加到数据框新列的列表的大小。它不应超过预期的长度。这将导致错误。

【讨论】:

    猜你喜欢
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 2021-12-28
    • 2019-07-28
    • 2019-10-08
    相关资源
    最近更新 更多