Pandas: 如何获取索引之间的行?
Pandas: How to get rows between indexes?
大家好。
我的问题是:我无法在多行之间获取行(数据)。
我有一本 excel 一本书,里面有 21 sheet 篇。每个 table 在每个 sheet 上都有一些不同的变化。桌子没有头(制造它的人都是白痴)。但是 table 中第一列和第二列的值相同。所以,我得到了它们的索引,但是如何在它们之间获取行呢?
import pandas as pd
file_path = r"./files/menu.xlsx"
df = pd.read_excel(file_path)
xl = pd.ExcelFile(file_path).sheet_names
breakfast = df.loc[df['Unnamed: 0'] == 'breakfast'].index[0] # index is "5"
dinner = df.loc[df['Unnamed: 0'] == 'dinner'].index[0] # index is "14"
heads = df.iloc[[int(breakfast) - 1]]
您可以在iloc()
操作中使用范围start:end
来指定开始和结束索引。请记住,开始索引包含在结果中,而结束索引被排除在外:
rows_between = df.iloc[int(breakfast)+1:int(dinner)]
大家好。
我的问题是:我无法在多行之间获取行(数据)。
我有一本 excel 一本书,里面有 21 sheet 篇。每个 table 在每个 sheet 上都有一些不同的变化。桌子没有头(制造它的人都是白痴)。但是 table 中第一列和第二列的值相同。所以,我得到了它们的索引,但是如何在它们之间获取行呢?
import pandas as pd
file_path = r"./files/menu.xlsx"
df = pd.read_excel(file_path)
xl = pd.ExcelFile(file_path).sheet_names
breakfast = df.loc[df['Unnamed: 0'] == 'breakfast'].index[0] # index is "5"
dinner = df.loc[df['Unnamed: 0'] == 'dinner'].index[0] # index is "14"
heads = df.iloc[[int(breakfast) - 1]]
您可以在iloc()
操作中使用范围start:end
来指定开始和结束索引。请记住,开始索引包含在结果中,而结束索引被排除在外:
rows_between = df.iloc[int(breakfast)+1:int(dinner)]