indexerror:索引越过iloc

时间:2015-05-20 16:23:43

标签: python pandas

每当我在mysql中使用pandas sql进行查询时结果只有一行,我就无法从中选择值。

我的命令是:

result = psql.read_frame("select id,name,age from tb1 where id=1", con=conn)

然后它返回一个数据帧。但是我希望能够做到:

age = result['age'] 

但这不可能,因为它是一个数据帧。 (它创建了一个行的索引,所以这里是0)所以当我这样做时,我想把它变成一个系列或字典:

result = result.iloc[0]

我得到了

{'id': 1, 'name':'john','age':46} 

当我尝试:

result = result.iloc[0].to_dict()

它有效,但我得到一个错误IndexError:index out of bounds。

如何创建此单行数据帧的系列或字典?

1 个答案:

答案 0 :(得分:0)

只需将列选择器包含在loc中,然后使用':'表示所有列:

result = result.iloc[0, :].to_dict()

假设第零行是您希望转换为字典的行。

相关问题