Reputation:
I am trying to convert units within a Pandas Series.
df["he"] returns a Pandas Series:
0 5'10"
1 5'2"
...
The below variable num1
should extract the number 5. Whereas num2
should extract the number 7.
The code works for 5'7"
but wouldn't work for 5'10"
How can I change from x[2:]
to something that would extract everything before '
?
In the past I have used functions like index()
and find()
- however, I'm new to Pandas and struggling to know how I can implement these.
def conversion(x):
num1 = int(x[:1])
num2 = int(x[2:3])
return (num1 * 12 + num2) * 2.54
df["he"] = df["he"].apply(conversion)
Upvotes: 0
Views: 46
Reputation: 76
Looks like your values are in string format. Split is a great string method to accomplish your task.
def conversion(x):
spl = x.split("'")
num1 = int(spl[0])
num2 = int(spl[1])
return (num1 * 12 + num2) * 2.54
Upvotes: 1