【问题标题】:Dataframe to dictionary without loosing decimal digits after comma数据框到字典,逗号后不丢失十进制数字
【发布时间】:2022-06-10 20:53:54
【问题描述】:

我尝试获取一个字典,其中包含逗号后两位数字的值,主要用于 0.0 作为 0.00。有什么建议我怎么能得到那个?我试图迭代抛出字典并将 0.0 替换为 0.00 但我无法解决它

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()

输出

df2:

      1     2
0  1.00  1.00
1  0.00  0.00
2  1.22  1.22
3  0.00  0.00

我的字典:

{'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}}

我想要:

{'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}}

【问题讨论】:

  • 如果你有真正的浮动,那是不可能的,你不能(也不应该)控制表示,也许你需要字符串?

标签: python pandas dataframe dictionary


【解决方案1】:

你能试试这个吗?

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

输出:

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'}}

我的 Google Colab 的屏幕截图:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 2017-10-06
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多