2017-09-28 108 views
0
def time_constant_values(time_value, df, band_list): 
     try: 
      time_value in df.index 
     except KeyError: 
      print('The time value does not exist!') 
     else: 
      constants = [] 
      for band in band_list: 
       constants.append(df.loc[time_value][band]) 
      t0_dict = dict(zip(band_list, constants)) 
      return t0_dict 

熊猫数据帧包含格式为hh:mm:ss的索引中的时间值。我在做什么除错部分?在索引中搜索熊猫数据帧中的值

我想访问特定的时间行为某些colummns,然后形成一个字段列标签作为键和数据值作为值。

谢谢!

+0

我在这里看到了很多东西,首先什么是你想在你的try块做的,并且有一个else语句没有如果。 – bhansa

+2

@bhansa其他部分是好的(有效的Python语法),还有其他问题... –

+0

如果您发现它有用,请接受答案,并坚持一个答案。谢谢。 –

回答

2

密钥的不存在不会抛出KeyError。它只是返回Falseelse始终运行,然后在对不存在的密钥进行索引时遇到问题。尝试使用if

def time_constant_values(df, time_value, band_list): 
    if time_value in df.index: 
     return df.loc[time_value, band_list].to_dict() 
+0

当我尝试用你的代码调用函数时,我得到“KeyError:'10:28:00'”,尽管我知道这是索引中的一个值。它有什么不同,我的索引值是timedelta对象? @COLDSPEED –

+1

@Brain_overflowed它不应该。我希望你的代码和我的回答完全一样。如果是,请尝试将'time_value'转换为timedelta。 –