python 在Excel中新增一列 您所在的位置:网站首页 excel新增列 python 在Excel中新增一列

python 在Excel中新增一列

2024-06-05 14:32| 来源: 网络整理| 查看: 265

1.在Excel中定义新列:

#定义新列需要用到columns.tolist()函数,具体代码如下: col_name=df.columns.tolist() col_name.insert(新列位置, '新列名称') wb=df.reindex(columns=col_name) #然后后面再接一行代码用来定义新列的计算规则。

2.将结果输出Excel文件:

df.to_excel("path to save")

对一个文件夹下所有Excel批量添加一列,整体代码:

import sys import os import pandas as pd from matplotlib import pyplot as plt import math import xlwt import xlsxwriter plt.rcParams['font.sans-serif']=['SimHei']#用来正常显示中文标签 plt.rcParams['axes.unicode_minus']=False#用来正常显示负号 path = r'file path' filenames = os.listdir(path) f = xlwt.Workbook(encoding='utf-8', style_compression=0) # 新建一个excel sheet = f.add_sheet('sheet1') # 新建一个sheet for i in filenames: excel_path = r'file name/' + i f = open(excel_path,'rb') # print(f) df = pd.read_excel(f) #定义新列 col_name = df.columns.tolist() col_name.insert(10,'1') #设置新增列的位置和名称 wb = df.reindex(columns = col_name) df['1'] = df['2'] - df['3'] #计算方式,根据自己设定 #To save it back as Excel df.to_excel("path to save/"+i) #Write DateFrame back as Excel file

参考资料: https://stackoverflow.com/questions/44811523/how-do-i-add-a-column-to-an-existing-excel-file-using-python

Excel中新增一列 python:https://www.cnblogs.com/guxingy/p/12916940.html



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有