设置可迭代错误时必须具有相等的 len 键和值

问题描述 投票:0回答:1

在将数据写入数据帧时,我遇到了这个问题“ValueError:使用可迭代设置时必须具有相等的 len 键和值”。这个 csv 有 98 行,我试图将值分配给我作为列表变量的列

variables = [positive_score,
            negative_score,
            polarity_score,
            subjectivity_score]
# write the values to the dataframe
var = var[:98]
for i, var in enumerate(variables):
  output_df.loc[i:97] = var
output_df.to_csv('Output_data.csv', index=False)
python nlp data-science file-handling sentiment-analysis
1个回答
0
投票

您可以使用 iloc 方法按行赋值。

variables = [positive_score, negative_score, polarity_score, subjectivity_score]

# Ensure all columns have the same length
min_length = min(len(var) for var in variables)
variables = [var[:min_length] for var in variables]

# Write the values to the dataframe row-wise using iloc
for i, var in enumerate(variables):
    output_df.iloc[:, i] = var

output_df.to_csv('Output_data.csv', index=False)
© www.soinside.com 2019 - 2024. All rights reserved.