繁体   English   中英

使用包含映射到值的索引的dict来使Pandas数据框

[英]Make Pandas dataframe from dict of dict that contain index mapped to value

我有一个dictdicts ,我试图使成Pandas DataFrame 将该dict构造为映射到将列索引映射为其值的dict索引,然后我希望DataFrame其他所有内容DataFrame 0。例如:

d = {0: {0:2, 2:5},
     1: {1:1, 3:2},
     2: {2:5}}

所以那么我希望DataFrame看起来像

index   c0   c1   c2   c3
    0  2.0  NaN  5.0  NaN
    1  NaN  1.0  NaN  2.0
    2  NaN  NaN  5.0  NaN

我目前正在计划编写一个函数,该函数将从d每个项目中yield一个元组,并将其用作创建DataFrame的可迭代DataFrame ,但是我对是否还有其他人做过类似的事情感兴趣。

只需简单地调用DataFrame.from_dict

pd.DataFrame.from_dict(d,'index').sort_index(axis=1)
     0    1    2    3
0  2.0  NaN  5.0  NaN
1  NaN  1.0  NaN  2.0
2  NaN  NaN  5.0  NaN

好吧,为什么不按常规方式进行处理和移置它:

>>> pd.DataFrame(d).T
     0    1    2    3
0  2.0  NaN  5.0  NaN
1  NaN  1.0  NaN  2.0
2  NaN  NaN  5.0  NaN
>>> 

经过时间测试其他建议,我发现我原来的方法要快得多。 我正在使用以下函数来制作传递给pd.DataFrame的迭代器

def row_factory(index_data, row_len):
    """
    Make a generator for iterating for index_data

    Parameters:
        index_data (dict): a dict mapping the a value to a dict of index mapped to values. All indexes not in
                           second dict are assumed to be None.
        row_len (int): length of row

    Example:
        index_data = {0: {0:2, 2:1}, 1: {1:1}} would yield [0, 2, None, 1] then [1, None, 1, None]
    """
    for key, data in index_data.items():
        # Initialize row with the key starting, then None for each value
        row = [key] + [None] * (row_len - 1)
        for index, value in data.items():
            # Only replace indexes that have a value
            row[index] = value
        yield row

df = pd.DataFrame(row_factory(d), 5)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM