编写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

猜你喜欢