如何将单个dataframe列转换为以列名为键的每一行的字典?

2024-09-27 22:11:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用Spacy的文档扩展功能。我需要将dataframe列转换为元组,元组由纯文本和具有列名-值对的字典组成。你知道吗

使用熊猫dataframe.to\ dict文件(orient='records')很接近,但不允许我仅使用一列或选择特定列。将to_dict()方法应用于单个dataframe列也不能使我更接近所需的布局。我应该采取不同的方法吗?你知道吗


import pandas as pd
df = pd.DataFrame({
    'Textitself': ['Just a text'],
    'Textkey': [502]
})
otherlayout = df.to_dict('records')
print(otherlayout)

下面是我试图获得的格式。你知道吗

desired_format = [('Just a text',{'Textkey' : 502 }), ('One more text', {'Textkey' : 103 })]

print(desired_format)

Tags: to方法textformatdataframedfdictpd
1条回答
网友
1楼 · 发布于 2024-09-27 22:11:45

有一种方法:

import pandas as pd
df = pd.DataFrame({
    'Textitself': ['Just a text','One more text'],
    'Textkey': [502, 103]
})
otherlayout = df.to_dict('records')
print(otherlayout)

desiredformat = [(i,dict(j)) for i,j in df.set_index("Textitself").iterrows()]
print(desiredformat)

输出为

[{'Textitself': 'Just a text', 'Textkey': 502}, {'Textitself': 'One more text', 'Textkey': 103}]


[('Just a text', {'Textkey': 502}), ('One more text', {'Textkey': 103})]

相关问题 更多 >

    热门问题