攝影或3C

Python: pandas.isna() 處理丟失的數據,如何刪除DataFrame的空列? df3 = df2.reset_index (drop=True) ; df_drop = df3.drop ( nanIdx, axis = 0 ).reset_index( drop = True ) 

範例參考pandas官網說明

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) 重要!
結果:
儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡