我下面有一个daframe。我想将其转换为字典。但是我不希望列名作为键。
data = {'0':[0.039169993,0.023344912], '1':[0.17865846,0.01093025],'2':[0.039170124,0.023344917], '3':[0.17865846,0.01093025],'4':[0.039170124,0.023344917]}
df= pd.DataFrame(data)
0.0 1.0 2.0 3.0 4.0
0 0.039169993 0.17865846 0.039170124 0.17865846 0.039170124
1 0.023344912 0.01093025 0.023344917 0.01093025 0.023344917
**Desired Result**:
{{0: 0.039169993, 1:0.023344912},
{0: 0.17865846, 1:0.01093025},
{0: 0.039170124, 1:0.023344917},
{0: 0.17865846, 1:0.01093025},
{0:0.039170124, 1:0.023344917}}
MyAttempt:
df.to_dict()
{'0': {0: 0.039169993, 1: 0.023344912},
'1': {0: 0.17865846, 1: 0.01093025},
'2': {0: 0.039170124, 1: 0.023344917},
'3': {0: 0.17865846, 1: 0.01093025},
'4': {0: 0.039170124, 1: 0.023344917}}
我不希望列名作为键。有可能吗?
答案 0 :(得分:0)
期望的结果具有一组词典的 format ,但是您不能拥有一组词典,因为词典不可散列,但是您可以有一个列表。
import pandas as pd
data = {'0': [0.039169993, 0.023344912], '1': [0.17865846, 0.01093025], '2': [0.039170124, 0.023344917],
'3': [0.17865846, 0.01093025], '4': [0.039170124, 0.023344917]}
df = pd.DataFrame(data)
result = list(df.to_dict().values())
print(result)
输出
[{0: 0.039170124, 1: 0.023344917}, {0: 0.039169993, 1: 0.023344912}, {0: 0.17865846, 1: 0.01093025}, {0: 0.17865846, 1: 0.01093025}, {0: 0.039170124, 1: 0.023344917}]
答案 1 :(得分:0)
您可以使用此:
df.T.to_dict(orient='records')
[{0: 0.039169993, 1: 0.023344911999999999},
{0: 0.17865845999999999, 1: 0.010930250000000001},
{0: 0.039170124000000001, 1: 0.023344917},
{0: 0.17865845999999999, 1: 0.010930250000000001},
{0: 0.039170124000000001, 1: 0.023344917}]
答案 2 :(得分:0)
您可以使用transpose
或T
和.to_dict(orient='records')
获得所需的输出,例如:
df.T.to_dict(orient='records')