So i have a column called owners that looks like this
'Owned by Terrick Inc.',
nan,
'Owned by MHPI Inc.',
'Owned by Zeman Homes & Neighborhoods',
'Owned by Santefort Neighborhood Properties',
'Owned by MHPI Inc.',
'Owned by MHPI Inc.',
nan,
2,
nan,
5,
'Owned by RHP Properties',
'Owned by Zeman Homes & Neighborhoods',
'Owned by Zeman Homes & Neighborhoods',
'Owned by Gateway Manufactured Home Community',
3,
nan,
'Owned by Zeman Homes & Neighborhoods',
'Owned by MHPI Inc.',
nan,
'Owned by Indian Trails LLC',
'Owned by Zeman Homes & Neighborhoods',
1,
'Owned by Lake View Manufactured Home Community',
5,
2,
'Owned by Zeman Homes & Neighborhoods'
I am trying to change all the values that are not number to a number 10. but for some reason it is not working. I tried 2 methods this is the first, but this just replaces the whole column with 9 so its not taking in my conditions.
df['Owner'][(df['Owner'] != 0) | (df['Owner'] != '1') | (df['Owner'] != '2') | (df['Owner'] != 3) | (df['Owner'] != 4) | (df['Owner'] != 5) | (df['Owner'] != 6)] = 9
the second method i used was a loop with an if statment. but this isnt doing anything to the list
for i in df['Owner']:
if i == 1:
pass
elif i == 2:
pass
elif i == 3:
pass
elif i == 4:
pass
elif i == 5:
pass
elif i == 6:
pass
elif i == 0:
pass
else:
i = 9
Thanks in advance
CodePudding user response:
You can map
the type
function, and compare to int
, then use where
to keep the integers and replace the rest with 10:
df['Owner'] = df['Owner'].where(df['Owner'].map(type).eq(int), 10)
output:
Owner
0 10
1 10
2 2
3 10
4 5
5 10
Used input:
from numpy import nan
df = pd.DataFrame({'Owner': ['Owned by MHPI Inc.', nan, 2, nan, 5, 'Owned by RHP Properties',]})
CodePudding user response:
df['Owner'] = [10 if type(x) is not int else x for x in df['Owner']]
Should do it. It reads like plain English like so often in Python.