Create a matrix from a text file - python

前端 未结 4 1547
清歌不尽
清歌不尽 2021-01-13 16:32

I would like to create a matrix from a three column file. I am sure it\'s something extremely easy, but I just do not understand how it needs to be done. Please be gentle, I

4条回答
  •  时光说笑
    2021-01-13 17:18

    Try:

    import pandas as pd
    import numpy as np
    
    raw = []
    with open('test.txt','r') as f:
        for line in f:
            raw.append(line.split())
    data = pd.DataFrame(raw,columns = ['row','column','value'])
    data_ind = data.set_index(['row','column']).unstack('column')
    np.array(data_ind.values,dtype=float))
    

    Output:

    array([[ 5., 4., 3.], [ nan, 2., 1.], [ nan, nan, 0.]])

提交回复
热议问题