Home > database >  How do I use pandas to add a column to a csv using a list?
How do I use pandas to add a column to a csv using a list?

Time:03-11

If I want to take a list with m number of elements and add it as the very first column to an existing csv file with m number of rows, what would be the easiest way to do that using pandas?

CodePudding user response:

You can copy the csv to a df then re-add the data back into the csv

import pandas as pd

df = pd.read_csv(file_path)
df['New_Column'] = 'Whatever'
df[['New_Column', 'Another_Column', 'Yet_Another_Column']].to_csv(file_path)

CodePudding user response:

use pd.insert to add your data from first column (if you have a simple list/column of values), I think it's very simple to use, just pass as first parameter the index where you wull insert these values for example:

import pandas as pd

# load your data from file or use this following example
# df = pd.read_csv ('data.csv')

df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'],
'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})

values=[1,2,3,4,5,6]

df.insert(0, column='new', value=values)

output:

index new key A
0 1 K0 A0
1 2 K1 A1
2 3 K2 A2
3 4 K3 A3
4 5 K4 A4
5 6 K5 A5
  • Related