user14462764
user14462764

Reputation: 153

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.

The attached picture shows the desired code

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

Upvotes: 0

Views: 111

Answers (1)

user14462764
user14462764

Reputation: 153

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

Upvotes: 1

Related Questions