无法使用非整数键按位置索引编制索引

时间:2019-08-29 09:28:49

标签: python pandas

我对python很陌生。我的代码如下-

reading_range = "0:54, 2:34" #this is my variable 
data.iloc[reading_range]  #this line is giving error ,because the value is coming as '0:54, 2:34'

但是我想要类似

data.iloc[0:54, 2:34]

预先感谢

2 个答案:

答案 0 :(得分:2)

对于元组和slice(..)对象,冒号和逗号是语法糖。您可以生成类似的内容:

reading_range = slice(0,54), slice(2,34)
data.iloc[reading_range]

答案 1 :(得分:2)

index = reading_range.split(',')
eval('data.iloc[{}, {}]'.format(index[0], index[1]))

查看eval()的作用:What does Python's eval() do?