使用 Python 的 pandas 库,你可以轻松地删除 Excel 文件中特定的几列。以下是一个简单的示例代码,可以帮助你实现这一功能。

import pandas as pd

# 读取 Excel 文件
df = pd.read_excel('file.xlsx')

# 删除特定的列
df.drop(['列1', '列2', '列3'], axis=1, inplace=True)

# 将修改后的数据保存为新的 Excel 文件
df.to_excel('new_file.xlsx', index=False)

你需要将 'file.xlsx' 替换为你要处理的 Excel 文件的名称,将 ['列1', '列2', '列3'] 替换为你要删除的列的名称列表。最后,将 'new_file.xlsx' 替换为你想要保存的新 Excel 文件的名称。

代码解释:

  1. 导入 pandas 库: import pandas as pd
  2. 读取 Excel 文件: 使用 pd.read_excel('file.xlsx') 读取名为 file.xlsx 的 Excel 文件,并将数据存储在 df 数据框中。
  3. 删除特定列: 使用 df.drop(['列1', '列2', '列3'], axis=1, inplace=True) 删除名为 '列1''列2''列3' 的列。
    • axis=1 表示删除列,而不是行。
    • inplace=True 表示直接修改原始数据框,而不是创建新的数据框。
  4. 保存修改后的数据: 使用 df.to_excel('new_file.xlsx', index=False) 将修改后的数据保存到名为 new_file.xlsx 的新 Excel 文件中。
    • index=False 表示不保存索引列。

使用示例:

假设你有一个名为 data.xlsx 的 Excel 文件,包含以下列:

  • 姓名
  • 年龄
  • 城市
  • 收入

你想要删除 年龄城市 列,并将结果保存到名为 modified_data.xlsx 的新文件中。

你需要将代码修改为:

import pandas as pd

df = pd.read_excel('data.xlsx')
df.drop(['年龄', '城市'], axis=1, inplace=True)
df.to_excel('modified_data.xlsx', index=False)

运行代码后,你将在同一目录下找到一个名为 modified_data.xlsx 的新文件,它包含 姓名收入 两列。

希望以上示例可以帮助你轻松地使用 Python 删除 Excel 文件中的特定列。

Python 删除 Excel 特定列:简单易懂的 Pandas 代码示例

原文地址: https://www.cveoy.top/t/topic/opLr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录