Convert Select Columns in Pandas Dataframe to Numpy Array

前端 未结 6 468
南方客
南方客 2020-12-13 02:05

I would like to convert everything but the first column of a pandas dataframe into a numpy array. For some reason using the columns= parameter of DataFram

6条回答
  •  天涯浪人
    2020-12-13 02:29

    Please use the Pandas to_numpy() method. Below is an example--

    >>> import pandas as pd
    >>> df = pd.DataFrame({"A":[1, 2], "B":[3, 4], "C":[5, 6]})
    >>> df 
        A  B  C
     0  1  3  5
     1  2  4  6
    >>> s_array = df[["A", "B", "C"]].to_numpy()
    >>> s_array
    
    array([[1, 3, 5],
       [2, 4, 6]]) 
    
    >>> t_array = df[["B", "C"]].to_numpy() 
    >>> print (t_array)
    
    [[3 5]
     [4 6]]
    

    Hope this helps. You can select any number of columns using

    columns = ['col1', 'col2', 'col3']
    df1 = df[columns]
    

    Then apply to_numpy() method.

提交回复
热议问题