Home > front end >  Add row numbers to CSV
Add row numbers to CSV

Time:08-12

Say I have this CSV:

apple
orange
banana
strawberry

How could I make it so that there's always the correct line number to the left of the item and adapt it in the case an item is added or removed from the csv.

Ex:

1,apple
2,orange
3,banana
4,strawberry

If I remove banana --> strawberry becomes line #3

1,apple
2,orange
3,strawberry

Then if I add banana:

1,apple
2,orange
3,strawberry
4,banana

I'm thinking of doing an independent function that initiates at the very end of when the CSV is done being edited. It'll check the file and arrange it on its own after all modifications have been made to the CSV.

CodePudding user response:

import pandas as pd
df = pd.read_csv('XYZ.csv')
df['row_num'] = df.reset_index().index
#df.to_csv("XYZ_new.csv")
print(df)

let me know if it helps

CodePudding user response:

You can use enumerate. By default it start with 0.

Code (Python3)

    csv_data = {
        'apple',
        'orange',
        'banana',
        'strawberry'
    }
    
    for index, key in enumerate(csv_data, start=1):
        # save to csv file
        print('{}\t{}'.format(index, key))
    
    # remove 'banana'
    print("\nremove 'banana'")
    new_csv_data = {key for index, key in enumerate(csv_data) if key != 'banana'}
    
    for index, val in enumerate(new_csv_data, start=1):
        # save to csv file
        print('{}\t{}'.format(index, val))
    
    # add 'banana'
    print("\nadd 'banana'")
    new_csv_data.add('banana')
   
    for index, val in enumerate(new_csv_data, start=1):
        # save to csv file
        print('{}\t{}'.format(index, val))

Output

1 orange
2 strawberry
3 apple
4 banana

remove 'banana'
1 orange
2 strawberry
3 apple

add 'banana'
1 orange
2 strawberry
3 apple
4 banana

  • Related