在两个条件下合并一些行 [英] merge some rows in two conditions

查看:41
本文介绍了在两个条件下合并一些行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想合并条件内的行.如果该行的长度少于20个字符,则将该行与上一行合并.但是我有两列,我想在第二列的代码中应用该条件,如果任何行包含的字符少于20个,则删除两列的行.

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.

我已经在这里获得了合并行的帮助,但是如果我现在只有一列,我将有不同的要求.我有两列,并且想在第二行中应用该操作,任何一行的行数少于20个字符时,请将该行与上一行合并,然后从两列中删除该行.

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

推荐答案

我通过将行设置为null并将其从CSV中删除来解决了此问题

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

这篇关于在两个条件下合并一些行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆