I have a python pandas dataframe with several columns and one column has 0
values. I want to replace the 0
values with the median
or mean
of this column.
data
is my dataframe
artist_hotness
is the column
mean_artist_hotness = data['artist_hotness'].dropna().mean()
if len(data.artist_hotness[ data.artist_hotness.isnull() ]) > 0:
data.artist_hotness.loc[ (data.artist_hotness.isnull()), 'artist_hotness'] = mean_artist_hotness
I tried this, but it is not working.
use pandas
replace
method:
df = pd.DataFrame({'a': [1,2,3,4,0,0,0,0], 'b': [2,3,4,6,0,5,3,8]})
df
a b
0 1 2
1 2 3
2 3 4
3 4 6
4 0 0
5 0 5
6 0 3
7 0 8
df['a']=df['a'].replace(0,df['a'].mean())
df
a b
0 1 2
1 2 3
2 3 4
3 4 6
4 1 0
5 1 5
6 1 3
7 1 8