我需要在for循环中重置熊猫数据框的帮助。这是我当前逻辑的伪代码-
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:设置为Iterable时,必须具有相同的len键和值
我通过这次错误调试学到的东西很难,也收获颇丰。经过进一步调查,我意识到错误肯定不是由于无法删除或清空数据帧df而引起的。他们两个都在工作。
不断声明的错误是在获取col3_output列表的逻辑期间发生的。我没有将其重置为空白以进行进一步的迭代(在示例示例中,我做了,但在原始示例中没有)。我应该说的另一件事是引发错误的行号。
对于面临类似错误的任何人,请检查以确保用于添加到数据框新列的列表大小。它不应超过预期的长度。这将导致错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句