2

I'm trying to read data from a textfile which consists of newline separated words I intend to use as the header for a separate csv file with no header.

I've loaded the textfile and dataset in via pandas but don't really know where to go from here.

names = pandas.read_csv('names.txt', header = None)
dataset = pandas.read_csv('dataset.csv, header = None')

The contents of the textfile look like this

dog
cat
sheep
...
  • Have you tried reading the names like this, https://stackoverflow.com/a/53536044/530160 , then passing the names as the names argument to read_csv? See docs: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html – Nick ODell Oct 29 '21 at 16:19
  • @NickODell not sure I can make sense of that. So there header text file is just words separated by newlines. The CSV file is then a traditional dataset. – xIIPANIKIIx Oct 29 '21 at 16:34

1 Answers1

0

You could probably read your .txt file in a different way, such as using splitlines() (as you can see from this example)

with open('names.txt') as f:
    header_names = f.read().splitlines()

header_names is now a list, and you could it to define the header (column names) of your dataframe:

dataset = pandas.read_csv('dataset.csv', header = None)
dataset.columns = header_names
Alessandro
  • 361
  • 1
  • 9