[英]converting panda series to object array as in javascript
I'm newbie in python. 我是python的新手。 I have a panda series like the following, 我有一个如下的熊猫系列,
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
I want to convert this as an object array as; 我想将其转换为对象数组;
[
{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}
]
Is it possible to do it in python? 是否可以在python中完成?
尝试这样:
arr_obj = df.to_dict(orient='records')
您需要使用带有参数orient='records'
to_json
来reset_index
:
df.reset_index().to_json(orient='records')
You can use df.to_dict
with the orient='records'
keyword. 您可以将df.to_dict
与orient='records'
关键字一起使用。
Original dataframe: 原始数据框:
>>> 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
Make 'timestamp'
a column: 将'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
Use df.to_dict
to get the final result: 使用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')}]
edit: It's unclear to me how exactly you want the timestamps to be represented in the final result. 编辑:对我来说还不清楚您希望在最终结果中如何精确地表示时间戳。 You might have to use to_json
over to_dict
as demonstrated in Sandeep Kadapa's answer . 您可能需要使用to_json
超过to_dict
作为证明桑迪普丘德达帕的答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.