programing

데이터 프레임에서 마지막 요소의 액세스 인덱스

nasanasas 2021. 1. 7. 08:02
반응형

데이터 프레임에서 마지막 요소의 액세스 인덱스


나는 이것을 둘러 보았지만 그것을 찾을 수없는 것 같습니다 (매우 사소한 것임에도 불구하고).

내가 가진 문제는 데이터 프레임의 첫 번째 및 마지막 항목에 대한 열 값을 검색하고 싶다는 것입니다. 하지만 내가 할 경우 :

df.ix[0]['date']

나는 얻다:

datetime.datetime(2011, 1, 10, 16, 0)

하지만 내가 할 경우 :

df[-1:]['date']

나는 얻다:

myIndex
13         2011-12-20 16:00:00
Name: mydate

다른 형식으로. 이상적으로는 데이터 프레임의 마지막 인덱스 값에 액세스하고 싶지만 방법을 찾을 수 없습니다.

인덱스 값으로 열 (IndexCopy)을 만들고 시도했습니다.

df.ix[df.tail(1)['IndexCopy']]['mydate']

그러나 이것은 또한 다른 형식을 생성합니다 (df.tail (1) [ 'IndexCopy']는 단순한 정수를 출력하지 않기 때문에).

어떤 아이디어?


이전 답변은 이제 다음으로 대체됩니다 .iloc.

>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
    date
17    10
18    18
19    26
20    34
21    42
22    50
23    58
>>> df["date"].iloc[0]
10
>>> df["date"].iloc[-1]
58

내가 생각할 수있는 가장 짧은 방법 .iget():

>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
    date
17    10
18    18
19    26
20    34
21    42
22    50
23    58
>>> df['date'].iget(0)
10
>>> df['date'].iget(-1)
58

또는 :

>>> df['date'][df.index[0]]
10
>>> df['date'][df.index[-1]]
58

There's also .first_valid_index() and .last_valid_index(), but depending on whether or not you want to rule out NaNs they might not be what you want.

Remember that df.ix[0] doesn't give you the first, but the one indexed by 0. For example, in the above case, df.ix[0] would produce

>>> df.ix[0]
Traceback (most recent call last):
  File "<ipython-input-489-494245247e87>", line 1, in <module>
    df.ix[0]
[...]
KeyError: 0

Combining @comte's answer and dmdip's answer in Get index of a row of a pandas dataframe as an integer

df.tail(1).index.item()

gives you the value of the index.


Note that indices are not always well defined not matter they are multi-indexed or single indexed. Modifying dataframes using indices might result in unexpected behavior. We will have an example with a multi-indexed case but note this is also true in a single-indexed case.

Say we have

df = pd.DataFrame({'x':[1,1,3,3], 'y':[3,3,5,5]}, index=[11,11,12,12]).stack()

11  x    1
    y    3
    x    1
    y    3
12  x    3
    y    5              # the index is (12, 'y')
    x    3
    y    5              # the index is also (12, 'y')

df.tail(1).index.item() # gives (12, 'y')

Trying to access the last element with the index df[12, "y"] yields

(12, y)    5
(12, y)    5
dtype: int64

If you attempt to modify the dataframe based on the index (12, y), you will modify two rows rather than one. Thus, even though we learned to access the value of last row's index, it might not be a good idea if you want to change the values of last row based on its index as there could be many that share the same index. You should use df.iloc[-1] to access last row in this case though.

Reference

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.item.html


df.tail(1).index 

seems the most readable


It may be too late now, I use index method to retrieve last index of a DataFrame, then use [-1] to get the last values:

For example,

df = pd.DataFrame(np.zeros((4, 1)), columns=['A'])
print(f'df:\n{df}\n')

print(f'Index = {df.index}\n')
print(f'Last index = {df.index[-1]}')

The output is

df:
     A
0  0.0
1  0.0
2  0.0
3  0.0

Index = RangeIndex(start=0, stop=4, step=1)

Last index = 3

ReferenceURL : https://stackoverflow.com/questions/15862034/access-index-of-last-element-in-data-frame

반응형