Ich denke, Sie können mask
verwenden und Parameter skipna=True
zu mean
statt dropna
hinzufügen. Auch braucht Zustand data.artist_hotness == 0
ändern, wenn 0
Werte oder data.artist_hotness.isnull()
ersetzen müssen, wenn ersetzen müssen NaN
Werte:
import pandas as pd
import numpy as np
data = pd.DataFrame({'artist_hotness': [0,1,5,np.nan]})
print (data)
artist_hotness
0 0.0
1 1.0
2 5.0
3 NaN
mean_artist_hotness = data['artist_hotness'].mean(skipna=True)
print (mean_artist_hotness)
2.0
data['artist_hotness']=data.artist_hotness.mask(data.artist_hotness == 0,mean_artist_hotness)
print (data)
artist_hotness
0 2.0
1 1.0
2 5.0
3 NaN
Alternativ loc
verwenden, aber weglassen Spaltenname:
data.loc[data.artist_hotness == 0, 'artist_hotness'] = mean_artist_hotness
print (data)
artist_hotness
0 2.0
1 1.0
2 5.0
3 NaN
data.artist_hotness.loc[data.artist_hotness == 0, 'artist_hotness'] = mean_artist_hotness
print (data)
IndexingError: (0 True 1 False 2 False 3 False Name: artist_hotness, dtype: bool, 'artist_hotness')
Eine andere Lösung ist DataFrame.replace
mit Angabe von Spalten:
data=data.replace({'artist_hotness': {0: mean_artist_hotness}})
print (data)
aa artist_hotness
0 0.0 2.0
1 1.0 1.0
2 5.0 5.0
3 NaN NaN
Oder wenn brauchen ersetzen alle 0
Werte in allen Spalten:
import pandas as pd
import numpy as np
data = pd.DataFrame({'artist_hotness': [0,1,5,np.nan], 'aa': [0,1,5,np.nan]})
print (data)
aa artist_hotness
0 0.0 0.0
1 1.0 1.0
2 5.0 5.0
3 NaN NaN
mean_artist_hotness = data['artist_hotness'].mean(skipna=True)
print (mean_artist_hotness)
2.0
data=data.replace(0,mean_artist_hotness)
print (data)
aa artist_hotness
0 2.0 2.0
1 1.0 1.0
2 5.0 5.0
3 NaN NaN
Wenn benötigen ersetzen NaN
in allen Spalten verwenden DataFrame.fillna
:
data=data.fillna(mean_artist_hotness)
print (data)
aa artist_hotness
0 0.0 0.0
1 1.0 1.0
2 5.0 5.0
3 2.0 2.0
Aber wenn nur in einige Spalten Series.fillna
verwenden:
data['artist_hotness'] = data.artist_hotness.fillna(mean_artist_hotness)
print (data)
aa artist_hotness
0 0.0 0.0
1 1.0 1.0
2 5.0 5.0
3 NaN 2.0