Converts a large integer (or a string representation of an integer) to a friendly text representation like 1000000 to 1M or 1000000000 to 1B so it can show that way on the graph, I am pretty much new to data science, I look everywhere for possible way to do it I can't, i am sure the answer will help someone else too. Thanks!
Asked
Active
Viewed 99 times
-1
-
`int('1_000_000_000')` works just fine (on python 3.7+ i think). – Quang Hoang Jun 01 '22 at 15:21
-
yeah but the main thing is to show it as 1B on the chart to make it easier to read here is the lists Year = ['2016','2017','2018','2019','2020',] ContentSpend = ['6_880_000_000','8_910_000_000','12_000_000_000','13_900_000_000','11_800_000_000'] Profit =['379_000_000','839_000_000','1_600_000_000','2_600_000_000','4_500_000_000'] – charlesj509 Jun 01 '22 at 15:24
-
I'd just convert to numbers, then pyplot would put, e.g. `1e9` next to your axis (forgot what it's called). – Quang Hoang Jun 01 '22 at 15:28
2 Answers
1
def friendly_text(i):
if i >= 1000000000000:
return str(i / 1000000000000) + 'T'
if i >= 1000000000:
return str(i / 1000000000) + 'B'
if i >= 1000000:
return str(i / 1000000) + 'M'
if i >= 1000:
return str(i / 1000) + 'K'
print(friendly_text(2555))
print(friendly_text(241555))
print(friendly_text(241535555))
print(friendly_text(2415533347615))
print(friendly_text(2415537537355355515))
# will print:
# 2.555K
# 241.555K
# 241.535555M
# 2.415533347615T
# 2415537.5373553555T

Amir
- 129
- 4
0
The humanize library does a pretty good job of this. https://python-humanize.readthedocs.io/en/latest/number/
For example
intword("1000000")
returns
1.0 million

scotty3785
- 6,763
- 1
- 25
- 35