Pandas:如何获取数据帧第一行和最后一行的键(索引)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45320659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:05:58  来源:igfitidea点击:

Pandas: How do I get the key (index) of the first and last row of a dataframe

python-3.xpandas

提问by 576i

I have a dataframe (df) with a datetime index and one field "myfield"

我有一个带有日期时间索引和一个字段“myfield”的数据框 (df)

I want to find out the first and last datetime of the dataframe.

我想找出数据框的第一个和最后一个日期时间。

I can access the first and last dataframe element like this:

我可以像这样访问第一个和最后一个数据框元素:

df.iloc[0]
df.iloc[-1]

for df.iloc[0]I get the result:

因为df.iloc[0]我得到了结果:

myfield myfieldcontent

Name: 2017-07-24 00:00:00, dtype: float

我的字段我的字段内容

名称:2017-07-24 00:00:00,数据类型:float

How can I access the datetime of the row?

如何访问行的日期时间?

回答by jezrael

You can use select indexby [0]or [-1]:

您可以使用 select indexby[0][-1]

df = pd.DataFrame({'myfield':[1,4,5]}, index=pd.date_range('2015-01-01', periods=3))
print (df)
            myfield
2015-01-01        1
2015-01-02        4
2015-01-03        5

print (df.iloc[-1])
myfield    5
Name: 2015-01-03 00:00:00, dtype: int64

print (df.index[0])
2015-01-01 00:00:00

print (df.index[-1])
2015-01-03 00:00:00

回答by Chankey Pathak

jezrael's answeris perfect. Just to provide an alternative, if you insist on using locthen you should first reset_index.

jezrael的回答是完美的。只是为了提供一个替代方案,如果您坚持使用,loc那么您应该首先使用reset_index.

import pandas as pd

df = pd.DataFrame({'myfield': [1, 4, 5]}, index=pd.date_range('2015-01-01', periods=3))
df = df.reset_index()
print df['index'].iloc[0]
print df['index'].iloc[-1]