从多个dicts创建一个pandas DataFrame

tin*_*ect 20 pandas

我是pandas的新手,这是我在stackoverflow上的第一个问题,我正在尝试用熊猫做一些分析.

我有一些文本文件包含我想要处理的数据记录.文件的每一行与记录匹配,哪些字段在固定的位置并且具有固定数量的字符的长度.同一文件中有不同种类的记录,所有记录共享第一个字段,这两个字符取决于记录类型.举个例子:

Some file:
01Jhon      Smith     555-1234                                        
03Cow            Bos primigenius taurus        00401                  
01Jannette  Jhonson           00100000000                             
...


field    start  length   
type         1       2   *common to all records, example: 01 = person, 03 = animal
name         3      10
surname     13      10
phone       23       8
credit      31      11
fill of spaces
Run Code Online (Sandbox Code Playgroud)

我正在编写一些代码来将一条记录转换为字典:

person1 = {'type': 01, 'name': = 'Jhon', 'surname': = 'Smith', 'phone': '555-1234'}
person2 = {'type': 01, 'name': 'Jannette', 'surname': 'Jhonson', 'credit': 1000000.00}
animal1 = {'type': 03, 'cname': 'cow', 'sciname': 'Bos....', 'legs': 4, 'tails': 1 }
Run Code Online (Sandbox Code Playgroud)

如果字段为空(填充空格),则字典中不会出现.

对于所有类型的记录,我想创建一个带有dicts键作为列名的pandas DataFrame,我尝试使用pandas.DataFrame.from_dict()但没有成功.

这里有我的问题:有没有办法用熊猫这样做,所以dict键成为列名?有没有其他标准方法来处理这种文件?

DSM*_*DSM 21

要从字典中创建DataFrame,您可以传递字典列表:

>>> person1 = {'type': 01, 'name': 'Jhon', 'surname': 'Smith', 'phone': '555-1234'}
>>> person2 = {'type': 01, 'name': 'Jannette', 'surname': 'Jhonson', 'credit': 1000000.00}
>>> animal1 = {'type': 03, 'cname': 'cow', 'sciname': 'Bos....', 'legs': 4, 'tails': 1 }
>>> pd.DataFrame([person1])
   name     phone surname  type
0  Jhon  555-1234   Smith     1
>>> pd.DataFrame([person1, person2])
    credit      name     phone  surname  type
0      NaN      Jhon  555-1234    Smith     1
1  1000000  Jannette       NaN  Jhonson     1
>>> pd.DataFrame.from_dict([person1, person2])
    credit      name     phone  surname  type
0      NaN      Jhon  555-1234    Smith     1
1  1000000  Jannette       NaN  Jhonson     1
Run Code Online (Sandbox Code Playgroud)

对于两个不同格式的文件混合,并假设该文件是没有这么大,我们不能读取它们,并将它们存储在内存中的更基本的问题,我会使用StringIO,使一个对象,它是有点像一个文件但它只有我们想要的行,然后使用read_fwf(fixed-width-file).例如:

from StringIO import StringIO

def get_filelike_object(filename, line_prefix):
    s = StringIO()
    with open(filename, "r") as fp:
        for line in fp:
            if line.startswith(line_prefix):
                s.write(line)
    s.seek(0)
    return s
Run Code Online (Sandbox Code Playgroud)

然后

>>> type01 = get_filelike_object("animal.dat", "01")
>>> df = pd.read_fwf(type01, names="type name surname phone credit".split(), 
                     widths=[2, 10, 10, 8, 11], header=None)
>>> df
   type      name  surname     phone     credit
0     1      Jhon    Smith  555-1234        NaN
1     1  Jannette  Jhonson       NaN  100000000
Run Code Online (Sandbox Code Playgroud)

应该管用.当然,你也可以在pandas看到之前将文件分成不同的类型,这可能是最简单的.