设置Pandas索引的开始和结束的优雅方法是什么?

时间:2017-01-11 09:26:34

标签: python pandas

我想从Pandas数据框中检索带有可选的开始和结束索引的数据。例如,丑陋的方式就像这样

def get_data(self, start=None, end=None):
   if start is None and end is not None:
      return self.data[:end]
   if start is not None and end is None:
      return self.data[start:]
   if start is not None and end is not None:
      return self.data[start:end]

有没有优雅的方法来做到这一点?谢谢!

1 个答案:

答案 0 :(得分:2)

def get_data(self, start=None, end=None):
    idx = self.data.index
    start = idx[0] if start is None else start
    end = idx[-1] if end is None else end
    return self.data.loc[start:end]