Linebreaks as delimiters in Python numpy's loadtxt

Viewed 22

For example, my data file is like this:

Bahman Rhett
Mandla Devyn
Loukil
Zoran Nahuel

because loadtxt uses whitespace as the delimiter it separates names with surnames, how can i make linebreaks the delimiters? Another problem is that not all rows have the same amout of "columns", so it gives error. Should i use something other than numpy for this job?

1 Answers

It might be easier to use pandas to load the data file using read_csv. If you need a numpy array type, pandas then makes it easy to convert from a pandas dataframe to a numpy array with to_numpy.

# header = None indicates there is no header row
df = pandas.read_csv(DATA_FILE, header=None)

# or if you want to name the column:
df = pandas.read_csv(DATA_FILE, names=["my-col"])

# if you need it as numpy array type, you can convert via:
arr = df.to_numpy()

printing the dataframe shows:

         my-col
0  Bahman Rhett
1  Mandla Devyn
2        Loukil
3  Zoran Nahuel
Related