-1

I have the following text scraped from a URL as strings:

1.15M 
3.75M 
1.7M 
4.19M 
1.81M 
351.65K 

"M" stands for million and "K" for thousand

I am struggling to get the right code to change this to full integers:

1150000
3750000
1700000
4190000
1810000
351650

For all items there can also be variations like 1.5Kor 23.2Kor 25.254M so I find it hard to write a logic that covers this (still new to coding).

Any idea?

exec85
  • 447
  • 1
  • 5
  • 21
  • This should answer your question: https://stackoverflow.com/questions/39684548/convert-the-string-2-90k-to-2900-or-5-2m-to-5200000-in-pandas-dataframe – Roxy Aug 29 '21 at 21:06

2 Answers2

1

You can simply try this:

def convert_str_list(str_list, amnt_key):
    value_list = [int(float(i[:-1]) * 10 ** amnt_key[i[-1]]) for i in str_list]
    return value_list

def conver_str(amnt_str, amnt_key):
    value_list = int(float(amnt_str[:-1]) * 10 ** amnt_key[amnt_str[-1]])
    return value_list

str_list = ["1.15M", "3.75M", "1.7M", "4.19M", "1.81M", "351.65K", "150M", "360M", "2.6B", "3.7B"]
amnt_key = {'K': 3, 'M': 6, 'B': 9, 'T': 12}

print(convert_str_list(str_list=str_list, amnt_key=amnt_key))

for amnt_str in str_list:
    print(conver_str(amnt_str=amnt_str, amnt_key=amnt_key))

Output:

[1150000, 3750000, 1700000, 4190000, 1810000, 351650, 150000000, 360000000, 2600000000, 3700000000]
1150000
3750000
1700000
4190000
1810000
351650
150000000
360000000
2600000000
3700000000
Sabil
  • 3,750
  • 1
  • 5
  • 16
  • 1
    I don't think you need to divide by 1000 at the end, otherwise great answer (almost what I thought, but you were faster :)) – Matiiss Aug 29 '21 at 21:11
  • Yeah, you are right. That was a misconception. I convert amount to K – Sabil Aug 29 '21 at 21:12
1

Try this:

n = "356.6M"
if "K" in n:
    n2 = n.replace("K", "")
    full_int = float(n2) * 1000
elif "M" in n:
    n2 = n.replace("M", "")
    full_int = float(n2) * 1000000
print(int(full_int))
Sylvester Kruin
  • 3,294
  • 5
  • 16
  • 39