Python使用 pandas操作Excel文件并新增列数据

业务实现:对于原先的excel文件,我需要新增一个数据列,不同情况,列数据的值不同,分别为空白行、已爬取、已改名、爬取异常、改名未知异常

python 复制代码
# -*- coding: utf-8 -*-
import io
import os
import re
import sys

import numpy as np
import pandas as pd
import pandas.io.formats.excel
pandas.io.formats.excel.ExcelFormatter.header_style = None  # 表头不加粗

reload(sys)
sys.setdefaultencoding('utf-8')

def change_data(data):
    try:
        data = data.replace(' ', '')  # 删除空格
        data = re.sub(r'\([^)]*\)', '', data)  # 删除括号以及内容
        data = re.sub(r'\*', '', data)  # 删除*号
        return data
    except Exception:
        pass

# 文件夹名称
dir_name_set = set()
for item in os.listdir(unicode(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'country'), 'utf-8')):
    item = change_data(item)
    dir_name_set.add(item)

# 改名字典
spacial_name_dict = {}
with io.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'spacial_country.txt'), 'r', encoding='utf-8') as f:
    lines = f.readlines()
    for line in lines:
        line_split = line.strip().split(' ')
        name1 = change_data(line_split[0])
        if '/' in name1:
            name1 = name1.split('/')[0]
        name2 = change_data(line_split[1])
        if '/' in name2:
            name2 = name2.split('/')[0]
        spacial_name_dict[name1] = name2

filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'country.xlsx')
sheet_name='species_data'
df = pd.read_excel(filename, sheet_name=sheet_name)
dfc = df.copy()
idx = 1

# 处理每一行数据
for index, row in dfc.iterrows():  # 返回每一行的索引和对应的行数据
    name = row['name']
    try:
        if isinstance(name, float) and np.isnan(name):
            dfc.loc[index, 'status'] = '空白行'
        else:
            name = change_data(name)
            if name in dir_name_set:
                dfc.loc[index, 'status'] = '已爬取'
            elif name in spacial_name_dict.keys():
                if spacial_name_dict[name] in dir_name_set:
                    dfc.loc[index, 'status'] = '已改名为{}'.format(spacial_name_dict[name])
                else:
                    dfc.loc[index, 'status'] = '改名未知异常'
            else:
                dfc.loc[index, 'status'] = '爬取异常'
        if (index != 0 and index % 10000 == 0) or index == len(dfc) - 1:
            print index, idx
            if idx == 15:
                dfcc = dfc.copy()
                output_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'country_{}.xlsx'.format(idx))
                print 'output_path', output_path
                dfcc.to_excel(output_path, sheet_name=sheet_name, index=False, header=True)
            idx += 1
    except Exception as e:
        print name, e
相关推荐
AI数据皮皮侠4 小时前
中国博物馆数据
大数据·人工智能·python·深度学习·机器学习
wu_jing_sheng04 小时前
Python中使用HTTP 206状态码实现大文件下载的完整指南
开发语言·前端·python
程序员大雄学编程5 小时前
「用Python来学微积分」2. 函数图像的变换
python·数学·微积分
Shi_haoliu5 小时前
Vue2 + Office Add-in关于用vue项目于加载项控制excel单元格内容(Demo版)
前端·javascript·vue.js·node.js·html·excel·office
Q26433650235 小时前
【有源码】基于Python与Spark的火锅店数据可视化分析系统-基于机器学习的火锅店综合竞争力评估与可视化分析-基于用户画像聚类的火锅店市场细分与可视化研究
大数据·hadoop·python·机器学习·数据分析·spark·毕业设计
unicrom_深圳市由你创科技5 小时前
工业上位机,用Python+Qt还是C#+WPF?
python·qt·c#
njsgcs5 小时前
json转excel python pd
python·json·excel·pd
一晌小贪欢6 小时前
Python爬虫第7课:多线程与异步爬虫技术
开发语言·爬虫·python·网络爬虫·python爬虫·python3
RECRUITGUY6 小时前
Excel中将毫秒时间戳转换为标准时间格式
excel