我是Python的新手 - 我試圖替換NULL和空值('')值在列熊貓數據框與該列中最頻繁的項目。但我需要能夠爲數據框的所有列和所有行執行此操作。我寫了下面的代碼 - 但它需要很多時間來執行。你能幫我優化嗎?替換所有數據幀列中NULL和空值的相應列中最頻繁的Non Null項
感謝 Saptarshi
for column in df:
#Get the value and frequency from the column
tempDict = df[column].value_counts().to_dict()
#pop the entries for 'NULL' and '?'
tempDict.pop(b'NULL',None)
tempDict.pop(b'?',None)
#identify the max item of the remaining set
maxItem = max(tempDict)
#The next step is to replace all rows where '?' or 'null' appears with maxItem
#df_test[column] = df_test[column].str.replace(b'NULL', maxItem)
#df_test[column] = df_test[column].str.replace(b'?', maxItem)
df[column][df[column] == b'NULL'] = maxItem
df[column][df[column] == b'?'] = maxItem
當沒有「最頻繁」項目時(即所有值爲空,或者當多個項目並列時),您想要什麼行爲? – ASGM