How to read file with space separated values in pandas

后端 未结 3 1626
不思量自难忘°
不思量自难忘° 2020-11-27 02:56

I try to read the file into pandas. The file has values separated by space, but with different number of spaces I tried:

pd.read_csv(\'file.csv\', delimiter=         


        
相关标签:
3条回答
  • 2020-11-27 03:34

    you can use regex as the delimiter:

    pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")
    
    0 讨论(0)
  • 2020-11-27 03:38

    add delim_whitespace=True argument, it's faster than regex.

    0 讨论(0)
  • 2020-11-27 03:48

    The accepted answer doesn't appear to work with newer versions of Python so here's a more up to date example using a user defined Dialect:

     csv.register_dialect('skip_space', skipinitialspace=True)
     with open(my_file, 'r') as f:
          reader=csv.reader(f , delimiter=' ', dialect='skip_space')
          for item in reader:
              print(item)
    
    0 讨论(0)
提交回复
热议问题