0

is it possible to get access of last column of a data frame and last row of a data frame by using

.loc[]

I saw this link

    https://stackoverflow.com/questions/40144769/how-to-select-the-last-column-of-dataframe

but in this discussion no one spoke about loc . I would be appreciate if someone helps me to to solve this problem. thanks a lot.

alireza
  • 113
  • 6
  • why not use `.iloc` as per the link you shared? with `.loc` you will have to specify the index / column, see: https://stackoverflow.com/questions/31593201/how-are-iloc-and-loc-different if you know the index of the last row / column name of the last column, then use `.loc`. otherwise `.iloc` lets you select them by positional order – kelvt Jun 22 '22 at 05:05

3 Answers3

0

` df_test = pd.DataFrame([2012, 2015, 2010], columns=['start_date'])

df_test['end_date'] = [2014, 2017, 2020]

last_index = list(df_test.index)[-1]

last_col = list(df_test.columns)[-1]

df_test.loc[last_index, last_col] `

enter image description here

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 22 '22 at 05:17
0

I think this will work: df.iloc[-1:,-1:]

iqbal
  • 21
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 22 '22 at 05:28
0

That is what iloc is made for

The loc method locates data by label. The iloc method locates data by integer index. If no column names are defined, this would be the easiest way:

data = [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3]]
df = pd.DataFrame(data)
df.iloc[-1,:]

output:
0    3
1    3
2    3
3    3
4    3

Last row would be accordingly:

df.iloc[:,-1]

output:
0    1
1    2
2    3

If you still want to use loc, the last column you wish to refer to needs a name since location by interger indexing is not possible.

df = pd.DataFrame({'first_column': [50, 60], 'last_column': [100, 120]})

df.loc[:]['last_column']

output:
0    100
1    120
Jorgo
  • 62
  • 5