Convert string to float and keep % format [duplicate] - python

This question already has answers here:
Keep % format of float values
(3 answers)
Closed 4 years ago.
I initially had the columns below in string, and I converted them into float for some calculation purposes.
Growth1 Growth2
4,365.46% 124.48%
45.29% 2.222222222222%
251.48% 23.999999999999%
df[['Growth1', 'Growth2']] = df[['Growth1', 'Growth2']].replace('%|,', '', regex=True).astype(float, errors='ignore')/100
Growth1 Growth2
43.6546 1.2448
0.4529 0.02222222222222
2.5148 0.23999999999999
However, they are in decimal format and I want them to show in % format. But I can't just add {:,.2%}'.format after a line like:
df[['Growth1', 'Growth2']] = df[['Growth1', 'Growth2']].replace('%|,', '', regex=True).astype(float, errors='ignore')/100(formatters=[{:,.2%}'.format])
Is there any way that you can do to keep the float in % format and round it to the 2 decimal places with the least amount of code (like 1 or 2 lines)? Thank you.
Desired output:
Growth1 Growth2
4,365.46% 124.48%
45.29% 2.22%
251.48% 24.00% # or 23.99%, no big deal

It looks like the parameter you use for format is not correct. It should be {:,.2f}, and % outside:
Example:
>>> "{:,.2f}%".format(4365.46)
'4,365.46%'

Maybe using pandas style?
df.style.format("{:.2%}")
When you display the returned object from this call, like you normally would a dataframe, it'll have your columns formatted in the manner you've requested.

df['Growth1'] = pd.Series(['{0:.2f}%'.format(val * 100) for val in df['Growth1']], index = df.index)
The same for "Growth2" column.
Note: if you want to keep the original column, just name the new one something other than "Growth1"

Related

Python decimal format [duplicate]

This question already has answers here:
How to round values only for display in pandas while retaining original ones in the dataframe?
(1 answer)
Can a variable be used in Python to define decimal places
(3 answers)
Set Decimal Point Precision in a Pandas Dataframe
(2 answers)
Closed 8 months ago.
I've looked around and I cannot find an anwser to my question.
I need decimal formatting where the decimal can be different depending on the situation. For this situation I want to pass a variable containing the decimal value.
The values I'm getting from my pandas DataFrame are in this format 3.18e-06, which in this case needs to be turned into 8 decimals, e.g., 3.18123456
Can I either turn my pd DF into an 8 decimal based float64 or can i somehow convert 3.18e-06 into 8 decimals after grabbing it from my db?
Preferably I want to pass a variable containing the decimal for formatting.
Something like:
decimal = 0.00000001
{0:.{decimal}f}".format(a)
EDIT:
In the end, none of the suggested options did it for me. Maybe I didn't phrase my question well enough. I'll share my solution here for anyone else who might need it.
ticksize is a variable which changes depending on the Binance Trading pair you're using, it comes in a format like: 0.00001 or 0.0000001.
async def get_precision(ticksize):
a = '{:.{prec}f}'.format(ticksize, prec=15)
regex = "..(\d+1).*"
try:
b = re.match(regex, str(a))[1]
precision = len(b)
return precision
except Exception as e:
print(f'An exception has occured on get_precision - {e}')
return False
# this function returns the length of ticksize starting from the first 0 after the dot.
# Now that we have our precision we can use a string format to get what we need.
last_buy = '{:.{prec}f}'.format(a, prec=precision)
#returns: Last purchase price for XRPBTC: 0.00001588
float("8.99284722486562e-02") # 0.0899284722486562
and now with 'rounding'
"{:.8f}".format(float("8.99284722486562e-02")) # '0.08992847'

How to format Python code to always return this specific length [duplicate]

This question already has answers here:
Dynamically calculated zero padding in format string in python
(2 answers)
How do I pad a string with zeroes?
(19 answers)
Closed 9 months ago.
Sorry if this is a bit of a noob question. But moving on..
Say at the beginning of my code I set a variable, like this:
TestVar = 'A6'
But I later want it to print out as 000000A6
Or say it was
TestVar = 'C30'
I'd want it to print out as 00000C30
Basically always returning it with a length of 8
The reasoning for this is I've made a general script for modding a game, (I can link if asked) and you need to put in certain values which I want to have format automatically for ease of use. For example on running it'll print
Item ID Here:
And if you put in 166 it would convert the decimal number to hex which would be A6, however in order to be usable for all values (not just ones that are 2 digits once converted) I'm trying to make it detect it's length and format it with the 0s before.
Sorry if this doesnt make sense, in a simpler way of saying this, is there a way for it to detect the length of a variable? So for example in pseudo
TestVar = 'C30'
If TestVar length = 3
print('00000'+TestVar)
Print Result: 00000C30
Basically always returning it with a length of 8
That's what format strings do:
>>> print(f"{'C30':>08s}")
00000C30
As a sidenote, to output any number as 8-digit hex:
>>> print(f"{100:>08X}")
00000064
>>> print(f"{1024:>08X}")
00000400
See the documentation:
for f-strings (the f'I am an f-string' syntax);
for formatting syntax (the >08s and >08X thing).
Use string function rjust():
print(test.rjust(8,'0'))
The .zfill string method can be used.
For example:
s = 'C30'
s.zfill(8)
>>> '00000C30'
Try this code
txt = "A6"
x = txt.zfill(8)
print(x)
You can use string.zfill method
for example.
code = '3C0'
filledCode = code.zfill(8)
this method filled with zero the number of digit that you pass like a parameter
try something like this str.rjust() function
i = 1111
pad = '0'
n = 8
x = str(i).rjust(n, pad)
print(x) # 00001111

When rounding integer, don't add to the end [duplicate]

This question already has answers here:
How to implement conditional string formatting? [duplicate]
(3 answers)
Closed 1 year ago.
I currently am trying to work with a number that has variable decimal place lengths. It can either be an integer, or have up to 10 decimals i.e. 33.3333333. I wanted to restrict the number to only have 2 decimals when it exceeds the length, or maintain the original if it's less.
I've tried using "{:0:.2f}".format, but the problem is that for integers, it also adds .00 to the end of the string.
When I tried using round(3) it'll return 3.0.
Is there a method, preferably a single line, that can convert 3.333333 to 3.33 but still allow for 3 to stay as an int?
Try choosing the format as a function of the values wholeness:
"{d}" if int(a) == a else "{:0:.2f}"
Can you finish from there?
You can use a conditional expression to choose the format based on the type of the variable:
for x in (33.3333333, 3):
print(("{:0}" if isinstance(x, int) else "{:.2f}").format(x))
You could also implement it using a dictionary to map types to format strings:
formats = {int: "{:0}", float: "{:.2f}"}
for x in (33.3333333, 3):
print(formats.get(type(x)).format(x))

Python String to float [duplicate]

This question already has answers here:
Python: String will not convert to float [duplicate]
(3 answers)
Closed 6 years ago.
I'm trying to extract a float from a line in a text file, but i can't for the life of me understand how to convert the number in the line (str) into a float
for line in fh:
if not line.startswith("A specific string") : continue
count = count + 1
#linevalue gets the numbers in the line that i'm interested in, so in order
#to have only the numeric value i tried getting rid of the other text in the line by only
# selecting that range (20:26
linevalue = line[20:26]
float(linevalue)
print type(linevalue)
print linevalue
the attempted conversion with float(linevalue) is not going through, the output of the program remains e.g:
<type 'str'> 0.4323
Can anyone help me understand what am I missing ?
Thank you very much for your time.
I think you want:
linevalue = float(linevalue)
You were correctly converting the string value to a float, but you weren't saving that value anywhere. (Calling float doesn't modify the existing variable; it returns a new value.)

How to convert negative string to integer in pandas?(how to handle "-") [duplicate]

This question already has answers here:
Convert number strings with commas in pandas DataFrame to float
(4 answers)
Closed 7 years ago.
Here's my problem: I have a column of numbers in pandas.dataFrame. But there are certain numbers that need to be converted because they might be string's.
Here's how the column currently looks:
[1
-1,650.00
-3
...]
I want it all to be integers. My code was:
df['columnname'].astype(int)
However, when I convert -1,650.00 to integer I'm getting an error. Even when the code is
df['columnname'].astype(float)
df['columnname'].astype(int)
It still doesn't solve the problem. It says could not convert string to float: - and the "-" is still not handled.
Try this:
df['columnname'].replace(',','').astype(float)
Or:
float(df['columnname'].replace(',',''))
Float numbers use a dot to separate the integral part from the decimal part, not commas. Your vector should look something like this:
[1,
-1650.00,
-3,
]

Categories

Resources