編寫一個 Python 程式,從檔案中讀取 Excel 資料並讀取第一列和最後一列的所有行
假設,你的一個 Excel 檔名為 pandas.xlsx,儲存在你的位置。
解決方案
要解決此問題,我們將按照以下步驟進行操作 -
定義 pd.read_excel 方法從 pandas.xlsx 檔案中讀取資料並將其另存為 df
df = pd.read_excel('pandas.xlsx')
應用 df.iloc[:,0] 來列印第一列的所有行
df.iloc[:,0]
應用 df.iloc[:,-1] 來列印最後一列的所有行
df.iloc[:,-1]
示例
讓我們看看下面的實現以獲得更好的理解 -
import pandas as pd df = pd.read_csv('products.csv') print("all rows of first column is") print(df.iloc[:,0]) print("all rows of last column is") print(df.iloc[:,-1])
輸出
all rows of first column is 0 1 1 2 2 3 3 4 4 5 ... 95 96 96 97 97 98 98 99 99 100 Name: id, Length: 100, dtype: int64 all rows of last column is 0 2019 1 2020 2 2018 3 2018 4 2018 ... 95 2019 96 2019 97 2018 98 2020 99 2018 Name: productionYear, Length: 100, dtype: int64
廣告