Skip to main content
 首页 » 编程设计

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

2024年10月17日8pander-it

我想从带有可选开始和结束索引的 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] 

有什么优雅的方法可以做到这一点吗?谢谢!

请您参考如下方法:

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]