我將如何選擇以下 df 的第 2 行到第 4 行以獲得如下所示的所需輸出。我嘗試這樣做df = df.index.between(2,4),但出現以下錯誤:AttributeError: 'Int64Index' object has no attribute 'between' col 1 col 2 col 30 1 1 21 5 4 22 2 1 53 1 2 24 3 2 45 4 3 2所需輸出 col 1 col 2 col 32 2 1 53 1 2 24 3 2 4
6 回答

侃侃爾雅
TA貢獻1801條經驗 獲得超16個贊
從數據框中選擇行的最簡單方法是使用 .iloc[rows, columns] 函數 pandas 例如這里我選擇第 2 行到第 4 行
df1=pd.DataFrame({"a":[1,2,3,4,5,6,7],"b":[4,5,6,7,8,9,10]})
df1.iloc[1:3] #

萬千封印
TA貢獻1891條經驗 獲得超3個贊
between
不能作用于索引數據類型,只能作用于Series
.?to_series
因此,如果您想使用布爾掩碼,您首先需要使用以下命令將索引轉換為序列:
df
#? ? col1? col2? col3
# 0? ? ?1? ? ?1? ? ?2
# 1? ? ?5? ? ?4? ? ?2
# 2? ? ?2? ? ?1? ? ?5
# 3? ? ?1? ? ?2? ? ?2
# 4? ? ?3? ? ?2? ? ?4
# 5? ? ?4? ? ?3? ? ?2
df[df.index.to_series().between(2,4)]
#? ? col1? col2? col3
# 2? ? ?2? ? ?1? ? ?5
# 3? ? ?1? ? ?2? ? ?2
# 4? ? ?3? ? ?2? ? ?4
添加回答
舉報
0/150
提交
取消