Adding missing label line

Question:

I csv have a file with data lines, but it misses the label line.
This label line is a string, coma separated, ready to be appended on top.

import pandas as pd
data = pd.read_csv("C:\Users\Desktop\Trades-List.txt", sep=',')
labelLine = "label1,label2,label3"

How to add the ‘labelLine’ on top of data and make sure it is properly considered as the label line of the file?

Asked By: Robert Brax

||

Answers:

Parameter sep=',' is default, so should be removed, add names with splitted values for columns names:

labelLine = "label1,label2,label3"
data = pd.read_csv("C:\Users\Desktop\Trades-List.txt", names=labelLine.split(','))
Answered By: jezrael

Use the names parameter of read_csv after splitting to list with str.split:

import pandas as pd

labelLine = "label1,label2,label3"

data = pd.read_csv("C:\Users\Desktop\Trades-List.txt", sep=',',
                   names=labelLine.split(','))

Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.