繁体   English   中英

如何使用 iloc [] select pandas dataframe 的倒数第二行 []?

[英]How to select second last row of a pandas dataframe using iloc[]?

我从在线获取数据并将该数据存储在 pandas dataframe 中。 但问题是 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)

你能告诉我我们如何使用 iloc[] 仅使用倒数第二行或倒数第二行的任何特定单元格 select

df.iloc[-2]将为您提供所有列的倒数第二行信息。

如果你只想要一个特定的列, df.loc不喜欢减号,所以你可以这样做的一种方法是: df.loc[(df.shape[0]-2), 'your_column_name']

其中df.shape[0]获取您的行数,-2 从中删除 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:

dataframe
   0  1
0  1  2
1  3  4
2  5  6

second last row
[3 4]

您也可以使用take

# all columns
df.take([-2])

# specific column
df['foo'].take([-2])

暂无
暂无

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

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