Data loading using arrays in Python

前端 未结 3 1360
感情败类
感情败类 2021-01-21 20:17

Have a data in such format in .txt file:

UserId   WordID
  1       20
  1       30
  1       40
  2       25
  2       16
  3       56
  3       44
  3       12
         


        
3条回答
  •  广开言路
    2021-01-21 20:46

    If you are concerned with performance issues, like often numpy is better :

    df=pd.read_csv('file.txt')
    def numpyway():
        u,v=df.values.T
        ind=argsort(u,kind='mergesort') # stable sort to preserve order
        return np.split(v[ind],add(1,*where(diff(u[ind]))))
    
    
    In [12]: %timeit numpyway() # on 8000 lines
    10000 loops, best of 3: 250 µs per loop
    

    If 'UserId' is already sorted, it is yet three times faster.

提交回复
热议问题