我想將此資料框轉換為字典,其中一個標簽作為鍵,我將多個推文存盤為值。有人可以幫忙嗎?

uj5u.com熱心網友回復:
假設您的資料框是變數名稱是“df”,那么下面可能會有所幫助:
temp = df.groupby(['labels']).apply(lambda x: x['tweets'].tolist()).to_dict()
print(temp)
uj5u.com熱心網友回復:
要獲得預期的結果,您可以運行例如:
result = df.groupby('labels')['tweets'].apply(list).to_dict()
細節:
df.groupby('labels')- 對源行進行分組。['tweets']- 僅獲取推文列(來自每個組)。apply(list)- 將當前組中的推文轉換為串列。您甚至不需要使用任何顯式的lambda函式。到目前為止(groupby和apply的結果)是 pandasonic Series。to_dict()- 將此系列轉換為字典。
對于您的源資料(縮短一點),結果是:
{'EXP': ['if you missed', 'the emotional'],
'QUE': ['the neverending'],
'STM': ['katie couric', 'a yearold nigerian']}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/424161.html
上一篇:根據其他列的條件添加和更新熊貓列
