【发布时间】: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”。这就是为什么我需要删除数据框然后重新创建它。