I try to get a dictionary with values with two digits after comma mainly for 0.0 as 0.00. Any suggestion how I could get that? I tried to iterate throw the dictionary and replace 0.0 for 0.00 but I couldn't solve it
import pandas as pd
from tkinter import *
def create():
data = {'1': [0.99999, 0.00000, 1.22222, 0.000000], '2': [0.99999, 0.00000, 1.22222, 0.000000]}
df = pd.DataFrame(data)
df2 = df.round(decimals = 2)
print(df2)
my_dictionary = df2.to_dict()
print(my_dictionary)
window = Tk()
window.geometry("200x200")
button = Button(text="Convert",command=create)
button.pack()
window.mainloop()
Outputs
df2:
1 2
0 1.00 1.00
1 0.00 0.00
2 1.22 1.22
3 0.00 0.00
my_dictionary:
{'1': {0: 1.0, 1: 0.0, 2: 1.22, 3: 0.0}, '2': {0: 1.0, 1: 0.0, 2: 1.22, 3: 0.0}}
I would like to have:
{'1': {0: 1.0, 1: 0.00, 2: 1.22, 3: 0.00}, '2': {0: 1.0, 1: 0.00, 2: 1.22, 3: 0.00}}
CodePudding user response:
Could you try this please?
data = {'A':[0.99999, 0.00000, 1.22222, 0.000000], 'B':[0.99999, 0.00000, 1.22222, 0.000000]}
df = pd.DataFrame(data)
print(df.dtypes)
df.A = df.A.apply(lambda x : '{:.3f}'.format(x))
df.B = df.B.apply(lambda x : '{:.3f}'.format(x))
df1 = df.to_dict()
df1
Output:
A float64
B float64
dtype: object
{'A': {0: '1.000', 1: '0.000', 2: '1.222', 3: '0.000'},
'B': {0: '1.000', 1: '0.000', 2: '1.222', 3: '0.000'}}
Screenshot of my Google Colab: