繁体   English   中英

获取带索引的 pandas dataframe 第一行

[英]Get the pandas dataframe first row with index

最近我开始在我的工作中使用 Pandas 来处理一些传感器获得的数据我有一个字典,其中传感器值的格式如下:

data={
  2019-10-23 00:00:00: {
    key1: value1,
    key2: value2,
    ...
    keyN: valueN
  },
  2019-10-23 00:00:03: {
    key1: value1,
    key2: value2,
    ...
    keyN: valueN
  },
  ...
}

我创建了一个 pandas dataframe:

dataframe = pandas.DataFrame.from_dict(data, orient="index")

生成的 dataframe 如下所示:

Whole Dataframe:
                            co        no2  ...  temperature  illuminance
2019-10-23 00:00:43  298.66458   0.000000  ...    15.498970          0.0
2019-10-23 00:00:44  305.92203   0.000000  ...    15.498970          0.0
2019-10-23 00:00:37  298.66458   3.456714  ...    15.498970          0.0
2019-10-23 00:00:50  305.92203   0.000000  ...    15.498970          0.0
2019-10-23 00:00:45  305.92203   0.000000  ...    15.498970          0.0
...                        ...        ...  ...          ...          ...
2019-10-23 23:33:59  327.05542   0.000000  ...    14.740597          0.0
2019-10-23 23:38:37  296.85214   0.000000  ...    14.687190          0.0
2019-10-23 23:43:38  289.69748   0.000000  ...    14.612421          0.0
2019-10-23 23:50:38  282.21335  15.672545  ...    14.526970          0.0
2019-10-23 23:54:44  297.21220   0.000000  ...    14.505608          0.0

现在我需要能够获取第一行的值,我尝试使用.iloc[0]to_dict()来获取要通过 api rest 发送的字典:

selected_value = dataframe.iloc[0].to_json()

打印这个:

Selected value:
{"co":298.66458,"no2":3.456714,"o3":53.318943,"so2":0.0,"humidity":65.13771,"pm1":0.0198951,"pm10":0.0209116,"pm25":0.0209116,"temperature":15.49897,"illuminance":0.0}

但它不返回索引,我想得到这样的东西(或者至少包括索引):

{"2019-10-23 00:00:43": 
 {
   "co":298.66458, 
   "no2":3.456714, 
   "o3":53.318943, 
   "so2":0.0, 
   "humidity":65.13771,
   "pm1":0.0198951,
   "pm10":0.0209116,
   "pm25":0.0209116,
   "temperature":15.49897,
   "illuminance":0.0
  }
}

有什么办法可以做到这一点?

PD:表示我使用between_time方法每 10 分钟执行一些中间程序以获取传感器值

你可以使用head代替:

# example data
df = pd.DataFrame({'a':range(2), 'b':range(2,4)}, 
                  index=pd.to_datetime(['01/01/2018','02/01/2018']).strftime('%Y-%m-%d %H:%M:%S'))

print (df.head(1).to_json(orient='index'))
{"2018-01-01 00:00:00":{"a":0,"b":2}}
#or to_dict maybe
print (df.head(1).to_dict(orient='index'))
{'2018-01-01 00:00:00': {'a': 0, 'b': 2}}

由于您选择了索引,因此它不会返回它

如果您希望索引成为数据的一部分,您可以随时设置它:

df.reset_index(inplace=True)
df.rename(columns={df.columns[0]:'timestamp'},inplace=True)

执行df.iloc[0]也会像其他列一样返回timestamp

如果您不希望它成为数据的一部分,您始终可以使用dataframe.index直接构建您想要的内容:

import json
json.dumps({df.index[0]:df.iloc[0].to_dict()})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM