卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章43950本站已运行31022

python怎么读取excel文件程序

如何使用 python 读取 excel 文件?导入 pandas 库。使用 pd.read_excel() 函数加载 excel 文件。查看文件内容:df.head()。访问特定表格:df = pd.read_excel('path/to/excel_file.xlsx', sheet_name='sheet1')。访问特定单元格:value = df.iloc[row_index, column_index]。迭代行和列:for row in df.iterrows()。保存更改:df.to

python怎么读取excel文件程序

如何使用 Python 读取 Excel 文件

导入必要的库

首先,你需要导入 Pandas 库来读取 Excel 文件:

<code class="python">import pandas as pd

加载 Excel 文件

使用 pd.read_excel() 函数加载 Excel 文件:

<code class="python">df = pd.read_excel('path/to/excel_file.xlsx')

其中 path/to/excel_file.xlsx 是要加载的 Excel 文件的路径。

查看文件内容

要查看已加载文件的头五行为:

<code class="python">df.head()

访问特定表格和单元格

如果你有多个工作表,可以使用 sheet_name 参数指定要读取的工作表:

<code class="python">df = pd.read_excel('path/to/excel_file.xlsx', sheet_name='Sheet1')

要访问特定单元格,可以使用 ilocloc 函数:

<code class="python">value = df.iloc[row_index, column_index]

<code class="python">value = df.loc[row_label, column_label]

迭代行和列

你可以使用 Pandas 的迭代器来遍历行和列:

<code class="python">for row in df.iterrows():
    # row 是一个元组,包含行索引和行数据
    print(row)

for col in df.itercols():
    # col 是一个元组,包含列名和列数据
    print(col)

保存更改

如果对文件进行了更改,可以使用 to_excel() 函数保存更改:

<code class="python">df.to_excel('path/to/output_file.xlsx')
卓越飞翔博客
上一篇: python怎么读取pkl文件
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏