欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2021年03月06日 12:53:37   作者:不合格學(xué)霸  
這篇文章主要介紹了python 刪除空值且合并excel的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

適用條件

1:excel表比較多

2:excel的數(shù)據(jù)量比較大,不然的話excel篩選&手動(dòng)合并還是很舒服滴~

需求

取出【電話】列中不為空所對(duì)應(yīng)的行的值并且將幾張表給合并起來(lái)

來(lái)來(lái)來(lái),放代碼了!!

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)#了解打印進(jìn)度
  sheet2=pd.read_excel(source_xls[i]).fillna("")#有空格,填充函數(shù),填的空值。要加fillna,不然無(wú)法刪除空值所對(duì)應(yīng)的行
  sysptom = sheet2[sheet2['電話'] !=""]#篩選
  sysptoms=pd.concat([sysptoms,sysptom])#兩個(gè)dataframe合并,相當(dāng)于合并excel
  print(type(sysptom))
  sysptoms.to_excel(target_xls, index=False)#pandas寫入excel用.to_excel
print("ok")

補(bǔ)充:python 讀取excel數(shù)據(jù),遇到空單元格的處理方法

讀取excel表格時(shí),經(jīng)常遇到空單元格的情況,這時(shí)需要明確的是,空單元格在python中是什么格式,NULL?NAN還是什么?

在用 xlrd 函數(shù)讀入excel時(shí),空單元格其實(shí)是空字符串'' 形式

因此處理方法就很簡(jiǎn)單啦,如下:

infilename = r'D:\aajja.xlsx'
workbook = xlrd.open_workbook(infilename)
df = workbook.sheet_by_name('sheetname')
num_rows = df.nrows - 1 # 我這里是第一行不要,所以跳過(guò)了
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)

其實(shí)重點(diǎn)就一句:

if isinstance(rawVal, str) 

判斷該單元格數(shù)值是否為字符串,當(dāng)然如果你的excel中本來(lái)就有字符串格式數(shù)據(jù),這里可以更改為判斷是否為空字符串,稍微修改一下即可

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

最新評(píng)論