merge some rows in two conditions

一个人想着一个人 提交于 2021-01-29 11:11:05

问题


I want to merge rows within a condition. If the row is less than 20 characters long, combine that row with the previous row. But I have two columns and I want to apply the condition in the code in the second column, if any row contains less than 20 characters remove row for two columns.

I got help here already to merge rows but if I had one column now I have different requirements. I have two columns and want to apply the operation in the second row, any row have less than 20 char merge this row with the previous row and remove this row from two columns.

This the old code for merge and remove row but when I have one columns. Thank you for help. I'm try this code but doesn't give me result.

import csv 
import pandas as pd

df = pd.read_csv('Test.csv')

with open('Output.csv', mode='w', newline='', encoding='utf-16') as f:
    writer = csv.writer(f, delimiter=' ')
    rows = []
    for i, data in enumerate(df['Sentence']):
        if i + 1 == len(df['Sentence']):
            writer.writerow([data])
        elif len(df['Sentence'][i + 1]) < 20:
            writer.writerow([data + df['Sentence'][i + 1]])
            df.drop(df.index[[i + 1]])
        elif len(df['Sentence'][i + 1]) >= 20:
            writer.writerow([data])

回答1:


I solved this by make the row null then remove it from CSV

df = pd.read_csv('test.csv', encoding='utf-8')

with open('output.csv', mode='w', newline='', encoding='utf-16') as f:
    writer = csv.writer(f, delimiter=' ')
    rows = []
    for i, data in enumerate(df['Sentence']):
        if i + 1 == len(df['Sentence']):
            writer.writerow([data])
        elif len(df['Sentence'][i + 1]) < 19:
            writer.writerow([data + df['Sentence'][i + 1]])
            df['Sentence'][i + 1] = ''
        elif len(df['Sentence'][i + 1]) >= 19:
            writer.writerow([data])


来源:https://stackoverflow.com/questions/65589445/merge-some-rows-in-two-conditions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!