编写一个 Python 程序从文件中读取 Excel 数据并读取第一列和最后一列的所有行

pythonpandasserver side programmingprogramming更新于 2024/6/21 2:52:17

假设,您在您的位置存储了一个名为 pandas.xlsx 的 Excel 文件。

解决方案

为了解决这个问题,我们将按照下面给出的步骤 −

  • 定义 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

相关文章


有用资源