[英]How to select second last row of a pandas dataframe using iloc[]?
I fetch the data from online and store that data in a pandas dataframe.我从在线获取数据并将该数据存储在 pandas dataframe 中。 But the problem is the dataframe format is not same every time mainly numbers of rows.
但问题是 dataframe 格式每次都不相同,主要是行数。
Print(df.shape)
Output: (100, 9)
-- --
Print(df.shape)
Output: (33, 9)
-- --
Print(df.shape)
Output: (153, 9)
-- --
Print(df.shape)
Output: (148, 9)
Can you please tell me how we can select only second last row or second last row's any specific cell using iloc[]你能告诉我我们如何使用 iloc[] 仅使用倒数第二行或倒数第二行的任何特定单元格 select
df.iloc[-2]
will get you the penultimate row info for all columns. df.iloc[-2]
将为您提供所有列的倒数第二行信息。
If you want a specific column only, df.loc
doesn't like the minus sign, so one way you could do it would be: df.loc[(df.shape[0]-2), 'your_column_name']
如果你只想要一个特定的列,
df.loc
不喜欢减号,所以你可以这样做的一种方法是: df.loc[(df.shape[0]-2), 'your_column_name']
Where df.shape[0]
gets your row count, and -2 removes 2 from it to give you the index number for your penultimate row.其中
df.shape[0]
获取您的行数,-2 从中删除 2 为您提供倒数第二行的索引号。 Then you give it the required column name to only return that value.然后,您为其提供所需的列名以仅返回该值。
You can get the second row from the back using index -2.您可以使用索引 -2 从后面获取第二行。
import pandas as pd
import numpy as np
a = np.matrix('1 2; 3 4; 5 6')
p = pd.DataFrame(a)
print("dataframe\n" + str(p))
print("second last row\n" + str(np.array(p.iloc[-2])))
Output: Output:
dataframe
0 1
0 1 2
1 3 4
2 5 6
second last row
[3 4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.