如何在没有索引的情况下将数据帧转换为字典

我有一个数据帧 df如下:

| name  | coverage |
|-------|----------|
| Jason | 25.1     |

我想把它转换成字典。 我在 pandas中使用了以下命令:

dict=df.to_dict()

dict的输出结果如下:

{'coverage': {0: 25.1}, 'name': {0: 'Jason'}}

我不希望在我的输出 0。我相信这是捕获,因为在我的数据帧 df的列索引。 我可以做什么来消除 0在我的输出 (我不希望索引被捕获)预期产出:

{'coverage': 25.1, 'name': 'Jason'}
90473 次浏览
dict1 = df.to_dict('records')

or

dict2 = df.to_dict('list')

list: keys are column names, values are lists of column data

records: each row becomes a dictionary where key is column name and value is the data in the cell

When I see your dataset with 2 columns I see a series and not a dataframe.

Try this: d = df.set_index('name')['coverage'].to_dict() which will convert your dataframe to a series and output that.

However, if your intent is to have more columns and not a common key you could store them in an array instead using 'records'. d = df.to_dict('r'). `

Runnable code:

import pandas as pd


df = pd.DataFrame({
'name': ['Jason'],
'coverage': [25.1]
})


print(df.to_dict())
print(df.set_index('name')['coverage'].to_dict())
print(df.to_dict('r'))

Returns:

{'name': {0: 'Jason'}, 'coverage': {0: 25.1}}
{'Jason': 25.1}
[{'name': 'Jason', 'coverage': 25.1}]

And one more thing, try to avoid to use variable name dict as it is reserved.

if its just 1 column, slice the 1 column (it gets converted to Series) wrapping in a dict function

dict( myDF.iloc[:, -1] )
# [: , -1] means: return all rows, return last column)


{Jason: 25.1}

you can do something like this:

data.to_dict('list')


#output:
#{'Feeling low in energy-slowed down': [2, 4, 2, 4]}