简体   繁体   中英

merge some rows in two conditions

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])

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM