1.找出含有空值的行
方法:DataFrame[DataFrame.isnull().T.any()]
其中,isnull()能夠判斷數據中元素是否為空值;T為轉置;any()判斷該行是否有空值。
import pandas as pd
import numpy as np
n = np.arange(20, dtype=float).reshape(5,4)
n[2,3] = np.nan
index = ['index1', 'index2', 'index3', 'index4', 'index5']
columns = ['column1', 'column2', 'column3', 'column4']
frame3 = pd.DataFrame(data=n, index=index, columns=columns)
print(frame3[frame3.isnull().T.any()])
程序成功找到了第三行為有空值的行。
2.為什么加轉置
在代碼中,isnull()的結果需要求轉置之后,才能進行any()操作,這是為什么呢?
下面對比一下isnull轉置和非轉置的情況:
print(frame3.isnull().any())
print("========================")
print(frame3.isnull().T.any())
可見:
非轉置:frame3.isnull().any(),得到的每一列求any()計算的結果,輸出為列的Series。
轉置:frame3.isnull().T.any(),得到的每一行求any()計算的結果,輸出為行的Series。
---------------------