Is there a better method than mapping str to float then mapping to int?
Is there a better method than mapping str to float then mapping to int?
I need to merge two data frames. In df_A the key is an int. In df_B the key is a string ending in .0 e.g. '10003.0'.
I would like to convert the string in df_B to an int for merging. Is there a better way than mapping twice as seen below?
df_B['key'].map(float).map(int)
The syntax seems awkward to me. Is there a better solution?
def floatint(x): return int(float(x))
.map(floatint)
1 Answer
1
You can using to_numeric
to_numeric
pd.to_numeric(df_B['key'],downcast='integer')
It does work, but I actually timed slightly slower using that compared to
astype
– user3483203
Jun 29 at 17:05
astype
@jpp yep, just change it :-) thank you
– Wen
Jun 29 at 17:06
@user3483203 Yep, if speed do matter astype is the winner
– Wen
Jun 29 at 17:09
This was my first downvote. I know downvotes should be explained. The reason was because I felt the answer was written in the spirit of racing to an answer, rather than writing a detailed and thorough answer. Maybe you could link to the docs, or explain what the function and its arguments do? Just my suggestion. I might be totally off base. Thank you for the solution anyway!
– Jay Calamari
Jun 29 at 17:20
@JayCalamari Since here is not many logic behind it (why I did not explain too much), I can link the doc
– Wen
Jun 29 at 17:25
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
def floatint(x): return int(float(x))
...map(floatint)
?– user2864740
Jun 29 at 17:03