vendredi 29 janvier 2021

How to print specific output based on condition from name variable

I have a dataframe data like that :

data

ANd I would like an output like that :

  • name1

    sentences1

    sentences2

    sentences3

  • name2

    sentences4

  • name3

    sentences5

    sentences6

Here's what I did so far :

first = True

for i in range(0, data.shape[0]):
    if data['Name'][i+1] == data['Name'][i] :
        if first:
            first = False
            print(data['Name'][i])
            print()
            print(data['Sentences'][i])
        else:
            print()
            print(data['Sentences'][i])
           
    if data['Name'][i] != data['Name'][i+1] :
        print(data['Name'][i])
        print(data['Sentences'][i])
       
    else :
        print()

But that doesn't give me the right output, the name aren't print at the place I wanted. I think I misplace or forget something in my loop but what ?

Thanks

EDIT : I think I figured it out ! I would like to know if I'm right, that's what I change in my code :

first = True

for i in range(0, data.shape[0]):
    if data['Name'][i+1] == data['Name'][i] :
        if first:
            first = False
            print(data['Name'][i])
            print()
            print(data['Sentences'][i])
        else:
            print()
            print(data['Sentences'][i])
           
    if data['Name'][i] != data['Name'][i+1] :
        print(data['Name'][i+1]) #i+1 instead of i
        print(data['Sentences'][i+1])# i+1 instead of i
       
    else :
        print()

Aucun commentaire:

Enregistrer un commentaire