I am getting into a problem statement for a script where i need to change int to a string with a range like 1-10 , 11-20 and so on. Using simple if else in python is not a good option for bugger numbers. Does someone know of any function to help out with this in python?
for example:
i am reading the numbers from a pandas dataframe each cell has different numbers:
so if i put the number in like the function-
convertnumtorange(1) it should give "1-10"
convertnumtorange(27) it should give "21-30"
>Solution :
Try this:
def convertnumtorange(n):
b = (n - 1) // 10 * 10 + 10
a = b - 9
return f'{a}-{b}'
Examples:
>>> convertnumtorange(1)
'1-10'
>>> convertnumtorange(27)
'21-30'
Let’s say you have a data frame with numbers:
>>> import pandas as pd
>>> df = pd.DataFrame({'n': [1, 27]})
>>> df
n
0 1
1 27
>>> df['range'] = df['n'].apply(convertnumtorange)
>>> df
n range
0 1 1-10
1 27 21-30