我是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