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

2024-04-24 09:04:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有什么优雅的方法吗?谢谢!在


Tags: and数据selfnonepandasdatagetreturn
1条回答
网友
1楼 · 发布于 2024-04-24 09:04:17
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]

相关问题 更多 >