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) 重要!

結果:


![Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool_Series] 選取多個rows #bool_Series長度同rows, index也需要同df.index ,可以使用.equals() 確認: df.index.equals(mask.index) Python: pandas.DataFrame (df) 的取值: df [單一字串] 或df [list_of_strings] 選取一個或多個columns; df [切片] 或 df [bool_Series] 選取多個rows #bool_Series長度同rows, index也需要同df.index ,可以使用.equals() 確認: df.index.equals(mask.index)](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2025/04/20250420212553_0_6fb2c3.png?quality=90&zoom=2&ssl=1&resize=350%2C233)








近期留言