【问题标题】:Covert a dataframe into a matrix form将数据框转换为矩阵形式
【发布时间】:2019-10-15 19:13:25
【问题描述】:

我有一个如下所示的数据集:

state VDM  MDM  OM  
AP     1    2   5   
GOA    1    2   1   
GU     1    2   4   
KA     1    5   1   
MA     1    4   4

我试过这段代码:

aMat=df1000.as_matrix()
print(aMat)

这里 df1000 是数据集。

但是上面的代码给出了这个输出:

[['AP' 1 2 5]
 ['GOA' 1 2 1]
 ['GU' 1 2 4]
 ['KA' 1 5 1]
 ['MA' 1 4 4]]

我想创建一个如下所示的二维列表或矩阵:

[[1, 2, 5], [1, 2, 1], [1,  2,  4], [1, 5, 1], [1, 4, 4]]

【问题讨论】:

    标签: python-3.x pandas list matrix


    【解决方案1】:

    通过DataFrame.iloc选择所有没有first的列,通过DataFrame.astype将整数值转换为字符串,最后通过to_numpyDataFrame.values转换为numpy数组:

    #pandas 0.24+
    aMat=df1000.iloc[:, 1:].astype(str).to_numpy()
    #pandas below
    aMat=df1000.iloc[:, 1:].astype(str).values
    

    或者通过DataFrame.drop删除第一列:

    #pandas 0.24+
    aMat=df1000.drop('state', axis=1).astype(str).to_numpy()
    #pandas below
    aMat=df1000.drop('state', axis=1).astype(str).values
    

    【讨论】:

      【解决方案2】:

      你可以使用df.iloc[]:

      df.iloc[:,1:].to_numpy()
      

      array([[1, 2, 5],
         [1, 2, 1],
         [1, 2, 4],
         [1, 5, 1],
         [1, 4, 4]], dtype=int64)
      

      或者对于字符串矩阵:

      df.astype(str).iloc[:,1:].to_numpy()
      

      array([['1', '2', '5'],
         ['1', '2', '1'],
         ['1', '2', '4'],
         ['1', '5', '1'],
         ['1', '4', '4']], dtype=object)
      

      注意我们为什么不使用as_matrix()

      ".as_matrix 将在未来的版本中删除。改用 .values。"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-11
        相关资源
        最近更新 更多