如果你想要获取DataFrame的第4行数据,并且同时使用 .loc
和 .iloc
来获取,可以在同一个代码块中实现。以下是示例代码:
import pandas as pd
import numpy as np
# 创建一个示例DataFrame
data = {
'a': np.random.randint(1, 20, 10),
'b': np.random.randint(1, 20, 10),
'c': np.random.randint(1, 20, 10),
'd': np.random.randint(1, 20, 10),
'e': np.random.randint(1, 20, 10)
}
df = pd.DataFrame(data)
# 打印原始DataFrame
print("原始DataFrame:")
print(df)
# 使用 .iloc 获取第4行(索引从0开始)
fourth_row_by_iloc = df.iloc[3]
# 使用 .loc 获取第4行(索引从0开始)
fourth_row_by_loc = df.loc[3]
# 打印结果
print("\n使用 .iloc 获取第4行:")
print(fourth_row_by_iloc)
print("\n使用 .loc 获取第4行:")
print(fourth_row_by_loc)
在上面的代码中:
iloc[3]
表示获取索引位置为3的行,即第4行。loc[3]
表示获取标签为3的行,如果DataFrame是由默认整数索引创建的,那么 loc[3]
也会获取第4行。在打印结果时,你将看到 .iloc
和 .loc
分别获取的第4行数据。
注意,.loc
索引器通常用于访问标签索引的行/列,而 .iloc
索引器用于通过整数位置访问行/列。如果DataFrame的行索引是默认的整数序列(从0开始),那么 .loc
和 .iloc
在访问相同行时表现出相同的行为。