邊遍歷邊刪除報錯(先記錄行號,後集中刪除)
import pandas as pd
df = pd.read_excel('stu.xls')
# print(df.iat[1,0])#獲取一個單元格的值
# print(df.shape)#獲取排和列(第一排表頭不算)
del_hang = []
for row in range(df.shape[0]):
# for column in range(df.shape[1]):
# print(df.iat[row,column])#遍歷每一個單元格
if df.iat[row,1] == 'XXX':
del_hang.append(row)#邊遍歷邊刪除報錯(先記錄行號,後集中刪除)
#df = df.drop(labels=row)
#df.iat[row, 1] = 'abc'
for i in del_hang:
df = df.drop(labels=i) #根據行號刪除
df.to_excel('a.xlsx',index=False)
等效於
import pandas as pd
df = pd.read_excel('stu.xls')
df = df[df['列名']!='XXX']
df.to_excel('a.xlsx',index=False)