将包含索引映射到值的dict of dict转换为Pandas dataframe

2024-03-28 10:12:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dictdicts,我想把它变成一个PandasDataFramedict被构造为映射到dict的索引,该索引将列索引映射到它们的值,然后我希望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

我目前正计划编写一个函数,它将yield来自d的每个项的一个元组,并将其用作创建DataFrame的iterable,但我对是否有其他人做过类似的事情感兴趣


Tags: 函数内容dataframeindexnandict计划元组
3条回答

在测试了其他的建议之后,我发现我原来的方法要快得多。我使用下面的函数生成一个迭代器,并将其传递到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)

好吧,为什么不按常规的方式做并转换它:

>>> 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
>>> 

只需简单的呼叫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

相关问题 更多 >