import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3),\
index=[“a”, “c”, “e”, “f”, “h”],\
columns=[“one”, “two”, “three”])
df2 = df.reindex([“a”, “b”, “c”, “d”, “e”, “f”, “g”, “h”])
df2[“one”]:
df2[“one”].isna():
df2[“one”].isna().tolist()
得到一個bool list
以下處理可以刪除空白列:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3),\
index=[“a”, “c”, “e”, “f”, “h”],\
columns=[“one”, “two”, “three”])
df2 = df.reindex([“a”, “b”, “c”, “d”, “e”, “f”, “g”, “h”])
bool_list = df2[“one”].isna().tolist()
#[False, True, False, True, False, False, True, False]
nanIdx=[]
for i in range(len(bool_list)):
if bool_list[i] == True:nanIdx.append(i)
#nanIdx = [1, 3, 6]
df3 = df2.reset_index(drop=True)
#df2的index不是0,1,2,3…
df_drop = df3.drop(nanIdx,axis=0).reset_index(drop=True)
#對df2處理會出現
# KeyError: ‘[1, 3, 6] not found in axis’
#因為df2的index是a,b,c,d…
#如果df2的index沒有從0開始或沒連續,也要小心
#.reset_index(drop=True) 重要!
結果: