1

I am trying to create a dataframe where one of the fields is calculated using a function. To do this I use the following code:

import pandas as pd

def didSurvive(sex):
    return int(sex == "female")


titanic_df = pd.read_csv("test.csv")
submission = pd.DataFrame({
    "PassengerId": titanic_df["PassengerId"],
    "Survived": didSurvive(titanic_df["Sex"])
})
submission.to_csv('titanic-predictions.csv', index=False)

when I run this code I get the following error:

D:\Documents\kaggle\titanic>python predictor.py
File "predictor.py", line 3
def didSurvive() {
^
SyntaxError: invalid syntax
D:\Documents\kaggle\titanic>python predictor.py
D:\Documents\kaggle\titanic>python predictor.py
D:\Documents\kaggle\titanic>python predictor.py
Traceback (most recent call last):
File "predictor.py", line 10, in
"Survived": didSurvive(titanic_df["Sex"])
File "predictor.py", line 4, in didSurvive
return int(sex == "female")
File "C:\Python34\lib\site-packages\pandas\core\series.py", line 92, in wrapper
"{0}".format(str(converter)))
TypeError: cannot convert the series to
D:\Documents\kaggle\titanic>

I think what is happening is I'm trying to run the int() on a series of booleans instead of an individual boolean. How do I go about fixing this?

2 Answers 2

0

To convert the data type of a Series, you can use astype() function, this should work:

def didSurvive(sex):
    return (sex == "female").astype(int)
2
  • Nice that worked.... What was wrong with using int() and why does .astype() work?
    – user2417339
    Dec 11, 2016 at 0:56
  • As you have noticed, int() function takes a number or string and converts it to an integer. It is a base python function and doesn't take Series object as parameter. astype() is pandas built in function for type conversion.
    – Psidom
    Dec 11, 2016 at 1:00
0

You can also reformat data during the import from csv file

titanic_df = pd.read_csv("test.csv", converters={'Sex':didSurvive})
submission = pd.DataFrame(titanic_df, columns=['PassengerId', 'Sex'])
1
  • Is there any advantage or disadvantage to using this method rather than calling a function when creating a data frame like how psidom and I are doing it?
    – user2417339
    Dec 11, 2016 at 19:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.