Convert pandas dataframe to NumPy array

前端 未结 15 2331
别那么骄傲
别那么骄傲 2020-11-21 23:57

I am interested in knowing how to convert a pandas dataframe into a NumPy array.

dataframe:

import numpy as np
import pandas as pd

index = [1, 2, 3,         


        
15条回答
  •  无人共我
    2020-11-22 00:46

    Further to meteore's answer, I found the code

    df.index = df.index.astype('i8')
    

    doesn't work for me. So I put my code here for the convenience of others stuck with this issue.

    city_cluster_df = pd.read_csv(text_filepath, encoding='utf-8')
    # the field 'city_en' is a string, when converted to Numpy array, it will be an object
    city_cluster_arr = city_cluster_df[['city_en','lat','lon','cluster','cluster_filtered']].to_records()
    descr=city_cluster_arr.dtype.descr
    # change the field 'city_en' to string type (the index for 'city_en' here is 1 because before the field is the row index of dataframe)
    descr[1]=(descr[1][0], "S20")
    newArr=city_cluster_arr.astype(np.dtype(descr))
    

提交回复
热议问题