(新手)使用pandas操作EXCEL

2019-01-08 08:24:41来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

import pandas as pd
import numpy as np
from pandas import DataFrame,Series
#path = r'C:\Users\tsl\Desktop\数据.xlsx'
#一列数据前面添加字符串
def add_C(village_data):
village_data['电话'] = ['C%s' % y for y in village_data['电话']]
return village_data['电话']
#读取excel
data = pd.read_excel(r'C:\Users\tsl\Desktop\数据.xlsx')
#判定某列中是否有null,如果有删除null 行
if data['电话'].isnull().any():
#将excel里面空值修改
data['电话'] = data['电话'].fillna('999')
#得到999值的索引室号
data_index = data[data.电话=='999'].index.tolist()
#删除
data = data.drop(data_index)
#以街道分组
group_by_name = data.groupby('街道')
#需要groups得出具体结果
for i in group_by_name.groups:
village_data = data.loc[data['街道'] == i ]
add_C(village_data)
  #以楼栋分组
group_by_name_build = village_data.groupby('楼栋')
for build_name in group_by_name_build.groups:
build_data = village_data.loc[village_data['楼栋'] == build_name]
build_data = build_data.drop_duplicates(subset='室号', keep='first')
      #更改列的数据类型
build_data['室号'] = build_data['室号'].astype(np.str)
row_index = 0
for house_num in build_data['室号']:
if '-' in house_num:
house_num = house_num.replace('-','9') #并没有修改原内存地址的值,固需要赋值给原有内存地址
#选区某行某列并赋值
build_data.iat[row_index,2] = house_num
row_index +=1
del build_data['街道']
del build_data['楼栋']
#修改列名
build_data.columns = ['用户编码','指定开门','电话号码']
build_data['指定开门'] = '双门'
build_data_row_index = 0
for modify_num in build_data['用户编码']:
if len(modify_num) < 4:
modify_num = '0' + modify_num #并没有修改原内存地址的值,固需要赋值给原有内存地址
build_data.iat[build_data_row_index,0] = modify_num
build_data_row_index +=1
#保存/生成新的excle
DataFrame(build_data).to_excel('C:\\Users\\tsl\Desktop\info\%s.xls' % (build_name),sheet_name='Sheet1',index=False,header=True )

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:python爬虫入门八:多进程/多线程

下一篇:Scrapy用pipelines把字典保存为csv格式