Python对Excel中具体某几列进行数据预处理

Python对Excel中具体某几列进行数据预处理,第1张

1.利用python读取Excel中.xls文件中所有数据

#encoding=utf-8
import xlrd
import xlwt
from xlwt import *

fileName="test01.xls"
bk=xlrd.open_workbook(fileName)
shxrange=range(bk.nsheets)
try:
    sh=bk.sheet_by_name("Sheet1")
except:
    print ("代码出错")
nrows=sh.nrows #获取行数
book = Workbook(encoding='utf-8')
 
for i in range(1,nrows):
    j = 1
    row_data=sh.row_values(i)
    #col_data=sh.col_values(i)
    print(row_data)

2.利用python处理xlsx中某列数据

# 需要倒入两个包
import pandas as pd
import openpyxl.workbook
import collections

if __name__ == '__main__':
    data = pd.read_excel("./文件名.xlsx")
    # print(list(data))
    colu=['甲', '乙', '丙']
    res=pd.DataFrame(columns=colu)
    for row in data.itertuples():
        col=collections.defaultdict(str)
        for i in range(len(colu)):
            col[colu[i]]=str(row[i+1])

        #拼音转汉字
        if  str(col["甲"]).lower()=="Daima".lower():  #不区分大小写,把拼音换成汉字
            col["甲"]="代码"
        elif str(col["乙"]).lower()=="fangjia".lower(): 
            col["乙"] = "放假"
 
        # 如果该列中有值以A-开头,那么去掉A-,只保留A-后面对内容。
        if str(col["乙"]).startswith(("A-")):  
            col["乙"] = col["乙"][2:]  #从下标索引为2开始的内容
        # 如果该列中某个值以C开头,并且长度小于等于3,那么只保留C后面的内容;
        if str(col["乙"]).startswith(("C")): 
            if (len(str(col["乙"])) <= 3):
                col["乙"] = col["乙"][1:]

        #如果某列中值以f开头或者以f结尾,那么我们去掉f
        if str(col["丙"]).lower().startswith(("f")):
            col["丙"]=col["丙"][1:]
        if str(col["丙"]).lower().endswith(("f")):
            col["丙"]=col["丙"][:-1]

        res=res.append(col, ignore_index=True)
    #print(res)
    res.to_excel('data_result.xlsx')
    print("代码运行完成")

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/923497.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存