脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 删除空值且合并excel的操作

python 删除空值且合并excel的操作

2021-09-16 00:05不合格学霸 Python

这篇文章主要介绍了python 删除空值且合并excel的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

适用条件

1:excel表比较多

2:excel的数据量比较大,不然的话excel筛选&手动合并还是很舒服滴~

需求

取出【电话】列中不为空所对应的行的值并且将几张表给合并起来

来来来,放代码了!!

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import xlrd
import pandas as pd
import openpyxl
target_xls = "合并表1.xlsx"
source_xls = ["全1.xlsx", "全2.xlsx","全3.xlsx",\
       "全4.xlsx","全5.xlsx","全6.xlsx"]
sysptoms=pd.dataframe()
for i in range(len(source_xls)):
  print(i)#了解打印进度
  sheet2=pd.read_excel(source_xls[i]).fillna("")#有空格,填充函数,填的空值。要加fillna,不然无法删除空值所对应的行
  sysptom = sheet2[sheet2['电话'] !=""]#筛选
  sysptoms=pd.concat([sysptoms,sysptom])#两个dataframe合并,相当于合并excel
  print(type(sysptom))
  sysptoms.to_excel(target_xls, index=false)#pandas写入excel用.to_excel
print("ok")

python 删除空值且合并excel的操作

补充:python 读取excel数据,遇到空单元格的处理方法

读取excel表格时,经常遇到空单元格的情况,这时需要明确的是,空单元格在python中是什么格式,null?nan还是什么?

在用 xlrd 函数读入excel时,空单元格其实是空字符串'' 形式

因此处理方法就很简单啦,如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
infilename = r'd:\aajja.xlsx'
workbook = xlrd.open_workbook(infilename)
df = workbook.sheet_by_name('sheetname')
num_rows = df.nrows - 1 # 我这里是第一行不要,所以跳过了
num_cols = df.ncols
t = 0
im_data = np.zeros((num_rows, num_cols))
for curr_row in range(1, num_rows+1):
  for curr_col in range(num_cols):
    rawval = df.cell(curr_row, curr_col).value
    if isinstance(rawval, str):
      im_data[curr_row - 1, curr_col] = np.nan
    else:
      im_data[curr_row - 1, curr_col] = float(rawval)

其实重点就一句:

?
1
if isinstance(rawval, str)

判断该单元格数值是否为字符串,当然如果你的excel中本来就有字符串格式数据,这里可以更改为判断是否为空字符串,稍微修改一下即可

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/weixin_43275179/article/details/89643062

延伸 · 阅读

精彩推荐