0

I have a data frame df3= pd.DataFrame( {"a": ["21.7K","22.7K","1.7K"]} )

I would like to change the type of a to int, I try to replace "K" with "000", but the replace()method doesn't work even I set inplace = True. And it seems replacing with "000" also causes new problems with the inaccurate numbers. how can I change the data type to int?

  • 1
    Does this answer your question? [Implementing thousands (k, kk) interpreter](https://stackoverflow.com/questions/61835208/implementing-thousands-k-kk-interpreter) Although the language is different, algorithm doesn’t differ – nicael Mar 31 '22 at 23:20
  • See this answer and make it in python: https://stackoverflow.com/a/61835361/2963652 – nicael Mar 31 '22 at 23:21
  • To answer the question about `replace`: Note that `replace` and `str.replace` do different things. It is not entirely clear what you used, but I assume you used the former when you need the latter. – fsimonjetz Mar 31 '22 at 23:25
  • to replace `df3['a'].str.replace('K', '000')` but this gives `21.7000` so it would need more complex method - get string `"21.7"`, convert to `float` and multiply 1000, - and it may need `.apply()` – furas Apr 01 '22 at 01:16
  • if all values have `K`: `df3['a'].apply(lambda item: int(float(item[:-1])*1000))` – furas Apr 01 '22 at 01:22
  • @furas I only show the part of the data frame, the value also contains M, are there any ways to solve that? – Katherine Shi Apr 01 '22 at 17:08
  • you have solution in one of link in other comments - and I even added link at the top [Convert the string 2.90K to 2900 or 5.2M to 5200000 in pandas dataframe](https://stackoverflow.com/questions/39684548/convert-the-string-2-90k-to-2900-or-5-2m-to-5200000-in-pandas-dataframe). It would need to write function which compare last char `item[:-1]` with `K`, `M`, `G`, etc. and use `1_000`, `1_000_000`, etc. – furas Apr 01 '22 at 21:18

0 Answers0