【问题标题】:Read a csv with numpy array using pandas使用 pandas 读取带有 numpy 数组的 csv
【发布时间】:2015-09-04 23:42:47
【问题描述】:

我有一个包含 3 列 emotion, pixels, Usagecsv 文件,其中包含 35000 行,例如0,70 23 45 178 455,Training

我使用pandas.read_csvcsv 文件读取为pd.read_csv(filename, dtype={'emotion':np.int32, 'pixels':np.int32, 'Usage':str})

当我尝试上述操作时,它显示ValueError: invalid literal for long() with base 10: '70 23 45 178 455'?如何将像素列读取为numpy 数组?

【问题讨论】:

    标签: python csv numpy pandas


    【解决方案1】:

    请尝试以下代码 -

    df = pd.read_csv(filename, dtype={'emotion':np.int32, 'pixels':str, 'Usage':str})
    
    def makeArray(text):
        return np.fromstring(text,sep=' ')
    
    df['pixels'] = df['pixels'].apply(makeArray)
    

    【讨论】:

    • 您好,感谢您的帮助。现在显示TypeError: data type not understood。可能的错误是什么?
    【解决方案2】:

    我相信使用矢量化的str 方法会更快地拆分字符串并根据需要创建新的像素列,并concat 将新列添加到新的df:

    In [175]:
    # load the data
    import pandas as pd
    import io
    t="""emotion,pixels,Usage
    0,70 23 45 178 455,Training"""
    df = pd.read_csv(io.StringIO(t))
    df
    
    Out[175]:
       emotion            pixels     Usage
    0        0  70 23 45 178 455  Training
    
    In [177]:
    # now split the string and concat column-wise with the orig df
    df = pd.concat([df, df['pixels'].str.split(expand=True).astype(int)], axis=1)
    df
    Out[177]:
       emotion            pixels     Usage   0   1   2    3    4
    0        0  70 23 45 178 455  Training  70  23  45  178  455
    

    如果你特别想要一个扁平的 np 数组,你可以调用 .values 属性:

    In [181]:
    df['pixels'].str.split(expand=True).astype(int).values
    
    Out[181]:
    array([[ 70,  23,  45, 178, 455]])
    

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题并想出了一个技巧。将您的数据帧保存为.npy 文件。在加载它时,它将作为ndarray 加载。您可以使用 pandas.DataFrame 将 ndarray 转换为数据框供您使用。我发现这个解决方案比从字符串字段转换更容易。示例代码如下:

      import numpy as np
      import pandas as pd
      np.save('file_name.npy',dataframe_to_be_saved)
      #the dataframe is saved in 'file_name.npy' in your current working directory
      
      #loading the saved file into an ndarray
      arr=np.load('file_name.npy')
      df=pd.DataFrame(data=arr[:,1:],index=arr[:,0],columns=column_names)
      
      #df variable now stores your dataframe with the original datatypes
      

      【讨论】:

        猜你喜欢
        • 2022-11-12
        • 1970-01-01
        • 2018-07-29
        • 2021-12-06
        • 2013-08-19
        • 2016-05-22
        • 2018-07-05
        • 2015-07-31
        • 1970-01-01
        相关资源
        最近更新 更多