1
$\begingroup$

I have a txt file where values are randomly separated, sometimes there is a single space, and sometimes there are many. I am importing the file into pandas with pd.read_csv, but I get only one column in my DataFrame. How can I define the sep parameter to read the values properly?

$\endgroup$
1
$\begingroup$

Do you only need to differentiate between one or more spaces? If so, maybe you can make use of a regular expression separator as listed in the pandas docs.

Something like this:

pd.read_csv(... sep='\s+', ...)

Also, consider adding the parameter delim_whitespace as such:

pd.read_csv(..., delim_whitespace=True, ...)
$\endgroup$
1
  • $\begingroup$ Thank you. I think I've found some other way. I will try with read_fwf. I think I will be able to cover most of the values with that instead of read_csv $\endgroup$ Feb 19 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.