简体   繁体   English

如何使用 .loc[] 访问数据框的最后一列?

[英]how to get access of last column of a dataframe by using .loc[]?

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 .但在这次讨论中,没有人谈到 loc 。 I would be appreciate if someone helps me to to solve this problem.如果有人帮助我解决这个问题,我将不胜感激。 thanks a lot.多谢。

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

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

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

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

df_test.loc[last_index, last_col] ` df_test.loc[last_index, last_col] `

enter image description here在此处输入图像描述

我认为这会起作用:df.iloc[-1:,-1:]

That is what iloc is made for这就是iloc的用途

The loc method locates data by label. loc方法通过标签定位数据。 The iloc method locates data by integer index. iloc方法通过整数索引定位数据。 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.如果您仍想使用loc ,您希望引用的最后一列需要一个名称,因为通过整数索引定位是不可能的。

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

df.loc[:]['last_column']

output:
0    100
1    120

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM