Use strip('%') , as:
In [9]: "99.5%".strip('%')
Out[9]: '99.5' #convert this to float using float() and divide by 100
In [10]: def p2f(x):
....: return float(x.strip('%'))/100
....:
In [12]: p2f("99%")
Out[12]: 0.98999999999999999
In [13]: p2f("99.5%")
Out[13]: 0.995
Answer from Ashwini Chaudhary on Stack OverflowUse strip('%') , as:
In [9]: "99.5%".strip('%')
Out[9]: '99.5' #convert this to float using float() and divide by 100
In [10]: def p2f(x):
....: return float(x.strip('%'))/100
....:
In [12]: p2f("99%")
Out[12]: 0.98999999999999999
In [13]: p2f("99.5%")
Out[13]: 0.995
Simply replace the % by e-2 before parsing to float :
float("99.5%".replace('%', 'e-2'))
It's safer since the result will still be correct if there's no % used.
Videos
Hello! I am very, very new to Python. I am working on an assignment for school and I am really struggling to get this string converted to a percentage. Can anyone help??
print(str("%.2f" % intensity).ljust(16) + str(max_hr))
Since Python 3.0, str.format and format support a percentage presentation type:
>>> f"{1/3:.0%}"
'33%'
>>> "{:.0%}".format(1/3)
'33%'
>>> format(1/3, ".0%")
'33%'
Percentage. Multiplies the number by 100 and displays in fixed (
'f') format, followed by a percent sign.
The .0 part of the format spec .0% indicates that you want zero digits of precision after the decimal point, because with f"{1/3:%}" you would get the string '33.333333%'.
It works with integers, floats, and decimals. See PEP 3101.
There is a way more convenient 'percent'-formatting option for the .format() format method:
>>> '{:.1%}'.format(1/3.0)
'33.3%'
There are two ways of string formatting in python and I've been consistently using the percentage (%) method until now:
"Today is %s." % datetime.now() # 2018-06-03 16:50:35.226194 "%d is a good number." % 5 # 5
I know this may not be very eloquent, but does the job well. One of the major irritants for me is the number to string conversion, I've faced that error so many times in the earlier days when I simply used to "There are " + x + " mangoes.". This works great in most other languages as they "auto-convert" the x from integer to string, but not python because of its "explicitness". But today, I learned of this new method of string.format() which does the same job, perhaps more eloquently:
"Today is {0}.".format(datetime.now()) # 2018-06-03 16:50:35.226194
"{0} is a good number.".format(5) # 5The only problem I'd imagine would be when you have to deal with long floats:
f = 1.234535666
"this is a floating point number: {0}".format(f) # 1.234535666Problem here is that it will output the entire float as it is without rounding, and here is where my percentage method has an edge!
"this is a floating point number: %.2f" % f # 1.23
Firstly, you can write e. g. {0:.2f} to specify a float with 2 decimals, see e. g. https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3
Secondly, the best formatting method is f-strings, see e. g. https://www.blog.pythonlibrary.org/2018/03/13/python-3-an-intro-to-f-strings/
of course .format() can do number formatting - "a number {:.2f}"! also you don't have to use explicit {0} indexing, you can go by position {} or use labels {a}.
https://docs.python.org/3.4/library/string.html#format-examples
You just discovered .format()? people are mostly migrating away from that to fstrings if they are using modern versions.
dude, you have to read the docs
You were very close with your df attempt. Try changing:
df['col'] = df['col'].astype(float)
to:
df['col'] = df['col'].str.rstrip('%').astype('float') / 100.0
# ^ use str funcs to elim '%' ^ divide by 100
# could also be: .str[:-1].astype(...
Pandas supports Python's string processing functions on string columns. Just precede the string function you want with .str and see if it does what you need. (This includes string slicing, too, of course.)
Above we utilize .str.rstrip() to get rid of the trailing percent sign, then we divide the array in its entirety by 100.0 to convert from percentage to actual value. For example, 45% is equivalent to 0.45.
Although .str.rstrip('%') could also just be .str[:-1], I prefer to explicitly remove the '%' rather than blindly removing the last char, just in case...
You can define a custom function to convert your percents to floats at read_csv() time:
# dummy data
temp1 = """index col
113 34%
122 50%
123 32%
301 12%"""
# Custom function taken from https://stackoverflow.com/questions/12432663/what-is-a-clean-way-to-convert-a-string-percent-to-a-float
def p2f(x):
return float(x.strip('%'))/100
# Pass to `converters` param as a dict...
df = pd.read_csv(io.StringIO(temp1), sep='\s+',index_col=[0], converters={'col':p2f})
df
col
index
113 0.34
122 0.50
123 0.32
301 0.12
# Check that dtypes really are floats
df.dtypes
col float64
dtype: object
My percent to float code is courtesy of ashwini's answer: What is a clean way to convert a string percent to a float?
So for my project one part of it is turning a decimal that as user would input and turn it into a decimal(It's supposed to be like a phone battery percentage). Im having trouble doing this so I need help. This is my input:
decimal = float(input("Enter a decimal: "))
So what would I code to turn whatever they put into a percent?