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

smdncfj3  于 2024-01-05  发布在  Python
关注(0)|答案(1)|浏览(138)

当我把数据写入一个数组时,我遇到了这个问题“ValueError:当用一个迭代器设置时,必须有相等的len键和值”。这个csv有98行,我试图把值赋给我作为列表变量的列。

  1. variables = [positive_score,
  2. negative_score,
  3. polarity_score,
  4. subjectivity_score]
  5. # write the values to the dataframe
  6. var = var[:98]
  7. for i, var in enumerate(variables):
  8. output_df.loc[i:97] = var
  9. output_df.to_csv('Output_data.csv', index=False)

字符串

iyfamqjs

iyfamqjs1#

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

  1. variables = [positive_score, negative_score, polarity_score, subjectivity_score]
  2. # Ensure all columns have the same length
  3. min_length = min(len(var) for var in variables)
  4. variables = [var[:min_length] for var in variables]
  5. # Write the values to the dataframe row-wise using iloc
  6. for i, var in enumerate(variables):
  7. output_df.iloc[:, i] = var
  8. output_df.to_csv('Output_data.csv', index=False)

字符串

相关问题