Skip to content Skip to sidebar Skip to footer

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 conditio

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

Post a Comment for "Merge Some Rows In Two Conditions"