【问题标题】:Python Dataframe Chunk Column Indexing IncorrectlyPython Dataframe 块列索引不正确
【发布时间】:2021-11-12 03:00:15
【问题描述】:

我正在学习 DataFrame 分块。我的伪代码很简单:

  1. 将 SOURCE_FILE 分解为多个块
  2. 加载块(带循环)
  3. 添加带有预测标签的列和带有置信度的另一列
  4. 将块写入驱动器
  5. 继续循环

第一个块按原样保存。其余块中的新列具有不正确的行索引。我无法弄清楚为什么会这样。感谢所有帮助。

另外,我的分块伪代码是否正确?如果这是正确的方法,我有点困惑。

# create chunks
for chunk in pd.read_csv(SOURCE_FILE, chunksize = CHUNK_SIZE):
    print('BATCH:', BATCH_NUMBER)
    
    # machine translate
    for row_index, text in enumerate(chunk.title):
        print('Text:', text)
        print('Row Index:', row_index)
        (label, confidence) = MODEL.predict(text)
        label = label[0]
        confidence = confidence[0]
        chunk.loc[row_index, 'Language'] = label[9:]
        chunk.loc[row_index, 'Confidence'] = confidence

    chunk.to_csv('Chunks/chunk' + str(BATCH_NUMBER) + '.csv' , index = False)
    BATCH_NUMBER += 1

You can see an image of the incorrect row indexing here

【问题讨论】:

    标签: python pandas dataframe chunking


    【解决方案1】:

    这有点晚了,但我想回答这个问题,以防将来有人遇到同样的问题。您正在尝试将两个新列连接到具有两列的现有块。 Pandas 使用列的索引并排连接列,第一个块的索引与两个新列的索引匹配,但其余块的索引更大,因此它们没有正确连接。使用

    重置其余块的索引
    chunk.index = range(len(chunk))
    

    它应该可以工作。

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 2021-11-22
      • 2021-11-11
      • 2018-08-20
      • 2023-04-05
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      相关资源
      最近更新 更多