python-3.x - 使用 Pandas 将字典条目扩展为行

标签 python-3.x pandas

我正在尝试使用 Python3 和 Pandas 将字典键和值扩展到它们自己的列中。下面是一个例子。并非所有字典都具有相同数量的项目,并且不能保证每个指标类型的键名称都匹配。

我想转换此数据框:

id  metric          dicts
1   some_metric_1   {'a': 161, 'b': 121}
2   some_metric_1   {'a': 152, 'c': 4}
2   some_metric_2   {'b': 162, 'a': 83}
3   some_metric_2   {'b': 103, 'z': 69}

创建者:

data = {'id': [1, 2, 2, 3], 'metric': ['some_metric_1', 'some_metric_1', 'some_metric_2', 'some_metric_2'], 'dicts': [{'a': 161, 'b': 121}, {'a': 152, 'c': 4}, {'b': 162, 'a': 83}, {'b': 103, 'z': 69}]}
df = pd.DataFrame.from_dict(data)

进入此:

id  metric          key value
1   some_metric_1   a   161
1   some_metric_1   b   121
2   some_metric_1   a   152
2   some_metric_1   c   4
2   some_metric_2   b   162
2   some_metric_2   a   83
3   some_metric_2   b   103
3   some_metric_2   z   69

最佳答案

您可以简单地迭代 DataFrame 的行并提取所需的值,如下所示。

现在请记住,下面的代码假设每个键只有 1 个值(即不会将值列表传递给字典键)。不过,无论按键数量多少,它都会起作用。

final_df = pd.DataFrame()

for row in df.iterrows():
    metric = row[1][1]      # get the value in the metric column
    i = row[1][0]           # get the id value
    for key, value in row[1][2].items():
        tmp_df = pd.DataFrame({
            'id':i,
            'metric':metric,
            'key': key,
            'value': value
        }, index=[0])

        final_df = final_df.append(tmp_df) # append the tmp_df to our final df

final_df.reset_index(drop=True)  # Reset the final DF index sinze we assign index 0 to each tmp df

输出

    id  metric        key   value
0   1   some_metric_1   a   161
1   1   some_metric_1   b   121
2   1   some_metric_1   c   152
3   2   some_metric_1   a   152
4   2   some_metric_1   c   4
5   2   some_metric_2   b   162
6   2   some_metric_2   a   83
7   3   some_metric_3   b   103
8   3   some_metric_3   z   69

以下是有关 df.append() 的更多信息.

关于python-3.x - 使用 Pandas 将字典条目扩展为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54916246/

相关文章:

python - 来自字符串列表的子数组

python - 在装饰器中扩展 Python 中的类

python-3.x - 槌中的Python主题建模错误

python-3.x - 上个月最后一天

pandas - 如何矢量化以加速 Dataframe apply pandas

python - 为什么 to_numeric() 将 string 转换为 float 而不是 int ?

python - Python lambda 捕获语义如何用于函数指针?

python - 为什么 tqdm.pandas() 不工作? - 如何解决PanelGroupBy导入问题

python - 使用列表理解修改数据框列

python - PyQ 中的 Kdb 数据库到 NumPy 数组