我想使用Spacy的Doc扩展功能。我需要将数据框列转换为仅包含文本和具有列名称值对的字典组成的元组。
使用pandas dataframe.to_dict(orient ='records')非常接近,但不允许我仅使用1列或选择特定的列。将to_dict()方法应用于单个数据框列也不会使我更接近所需的布局。我应该采取其他方法吗?
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)
答案 0 :(得分:0)
这是一种方法:
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})]