【问题标题】:Pandas: dataframe to array of rows with index as additional column熊猫:数据框到行数组,索引作为附加列
【发布时间】:2023-02-25 18:54:51
【问题描述】:

使用熊猫,当我打印数据框时,我的结果是

   Description Test
0        Some    3
1       Thing    e
2        Test  NaN

对于我的前端,我需要一些东西,一个是标题的对象数组,一个是行的对象数组。第一个不是问题,我是用columns 和一个函数做的。然而,这些行比较棘手。我需要这个结果:

[
{'id': 0, 'description':'some', 'test':'3'},
{'id': 1, 'description':'Thing', 'test':'e'},
{'id': 2, 'description':'Test', 'test':'NaN'},
]

NaN 是空的,我忘了给它传递一个值。我可以做一个函数,也许可以使用 pydash 和一些循环,但是有没有更快的方法来做到这一点?

【问题讨论】:

    标签: pandas


    【解决方案1】:

    将当前数字索引重置为命名列 id 并将数据框转换为记录列表,只需一行:

    df.reset_index(names='id').to_dict('records')
    

    [{'id': 0, 'Description': 'Some', 'Test': '3'},
     {'id': 1, 'Description': 'Thing', 'Test': 'e'},
     {'id': 2, 'Description': 'Test', 'Test': nan}]
    

    【讨论】:

    • 完美的!正是我想要的
    猜你喜欢
    • 2019-01-02
    • 2015-05-19
    • 2015-10-22
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 2016-08-24
    相关资源
    最近更新 更多