-1
# data is a dataframe
for i in data.Sex[0:]:
    if i == 'male':
        i=1
        print(i)
    elif i == 'female':
        i=0
        print(i)

The output prints the column in what I intended it to be, changing male to 1 and female to 0. However, the i=1 and i=0 seemed to not have worked. If I run

print(data.Sex)

then nothing changed

DavidG
  • 24,279
  • 14
  • 89
  • 82
newb24
  • 33
  • 4

1 Answers1

0

you are changing the element iterating, not the original dataframe,

try:

new_list = []
for element in data.Sex:
    if element == 'male':
        new_list.append(1)
    else:
        new_list.append(0)

data.Sex = new_list

I am pretty sure there is a more pythonic/elegant way of doing this but this would do it.

Also consider adding checks when data.Sex is not either male or female

E.Serra
  • 1,495
  • 11
  • 14