将panda系列转换为javascript中的对象数组

时间:2018-10-31 11:36:08

标签: python arrays pandas object series

我是python的新手。我有一个类似以下的熊猫系列,

                        count
timestamp                    
1980-10-05 01:12:00   56.4691
1980-10-05 01:13:00   54.9415
1980-10-05 01:14:00   52.0359
1980-10-05 01:15:00   47.7313
1980-10-05 01:16:00   50.5876
1980-10-05 01:17:00   48.2846
1980-10-05 01:18:00   44.6438
1980-10-05 01:19:00   42.3077
1980-10-05 01:20:00   38.8363
1980-10-05 01:21:00   41.0145
1980-10-05 01:22:00   39.5523
1980-10-05 01:23:00   38.9117
1980-10-05 01:24:00   37.3052
1980-10-05 01:25:00   36.1725
1980-10-05 01:26:00   37.5150
1980-10-05 01:27:00   38.1387
1980-10-05 01:28:00   39.5351
1980-10-05 01:29:00   38.1834
1980-10-05 01:30:00   37.5988
1980-10-05 01:31:00   43.6522
1980-10-05 01:32:00   47.9571
1980-10-05 13:08:00  210.0000
1980-10-05 13:18:00   40.0000
1980-10-05 13:28:00  250.0000
1980-10-05 13:38:00   40.0000

我想将其转换为对象数组;

[
    {timestamp: 1980-10-05 13:38:00, count: 40.0000},
    {timestamp: 1980-10-05 13:38:00, count: 40.0000},
    {timestamp: 1980-10-05 13:38:00, count: 40.0000},
    {timestamp: 1980-10-05 13:38:00, count: 40.0000}
]

是否可以在python中完成?

3 个答案:

答案 0 :(得分:0)

尝试这样:

arr_obj = df.to_dict(orient='records')

答案 1 :(得分:0)

您需要将$headerInfo的{​​{1}}和参数reset_index设置为:

to_json

答案 2 :(得分:0)

您可以将df.to_dictorient='records'关键字一起使用。

原始数据框:

>>> df.head()
>>> 
                       count
timestamp                   
1980-10-05 01:12:00  56.4691
1980-10-05 01:13:00  54.9415
1980-10-05 01:14:00  52.0359
1980-10-05 01:15:00  47.7313
1980-10-05 01:16:00  50.5876

'timestamp'设为一列:

>>> df = df.reset_index()
>>> df.head()
>>> 
            timestamp    count
0 1980-10-05 01:12:00  56.4691
1 1980-10-05 01:13:00  54.9415
2 1980-10-05 01:14:00  52.0359
3 1980-10-05 01:15:00  47.7313
4 1980-10-05 01:16:00  50.5876

使用df.to_dict获得最终结果:

>>> result = df.to_dict(orient='records')
>>> result[:5]
>>> 
[{'count': 56.4691, 'timestamp': Timestamp('1980-10-05 01:12:00')},
 {'count': 54.9415, 'timestamp': Timestamp('1980-10-05 01:13:00')},
 {'count': 52.0359, 'timestamp': Timestamp('1980-10-05 01:14:00')},
 {'count': 47.7313, 'timestamp': Timestamp('1980-10-05 01:15:00')},
 {'count': 50.5876, 'timestamp': Timestamp('1980-10-05 01:16:00')}] 

编辑:我不清楚您希望时间戳在最终结果中显示的精确程度。如Sandeep Kadapa's answer所示,您可能必须在to_json上使用to_dict