如何将dataframe的列转换成没有元组的一键多值字典?
How to convert dataframe columns into a dictionary with one key and multiple value without tuples?
我得到了一个像这样的大数据框,它基本上是这样的:
Name
km
Min
Max
test
24.6
43
555
test
63.9
31
666
我想把它变成像这样的字典:
{24.6: ["test",43,555],
63.9: ["test",31,666]}
到目前为止我发现的是 ,结果是:
dict(zip(zip(df.km),zip(df.Name, df.Min,df.Max)))
通过这种方式,我收到了一个元组字典,但我不会将键设为浮点数,将值设为字符串和浮点数。浮点数通常应保留 2 位小数。
我该怎么做?
在转置的 DataFrame 上使用 to_dict('list')
:
df.set_index('km').T.to_dict('list')
输出:
{24.6: ['test', 43, 555], 63.9: ['test', 31, 666]}
注意。请注意,如果您在“km”中有重复的值,因为您在字典中只能有唯一键,只有 latest 行将被保留
我得到了一个像这样的大数据框,它基本上是这样的:
Name | km | Min | Max |
---|---|---|---|
test | 24.6 | 43 | 555 |
test | 63.9 | 31 | 666 |
我想把它变成像这样的字典:
{24.6: ["test",43,555],
63.9: ["test",31,666]}
到目前为止我发现的是 ,结果是:
dict(zip(zip(df.km),zip(df.Name, df.Min,df.Max)))
通过这种方式,我收到了一个元组字典,但我不会将键设为浮点数,将值设为字符串和浮点数。浮点数通常应保留 2 位小数。
我该怎么做?
在转置的 DataFrame 上使用 to_dict('list')
:
df.set_index('km').T.to_dict('list')
输出:
{24.6: ['test', 43, 555], 63.9: ['test', 31, 666]}
注意。请注意,如果您在“km”中有重复的值,因为您在字典中只能有唯一键,只有 latest 行将被保留