【发布时间】:2019-06-10 07:08:24
【问题描述】:
我正在尝试使用嵌套的 DataFrame 并将其转换为嵌套的字典。
这是我的原始 DataFrame,具有以下唯一值:
输入:df.head(5)
输出:
reviewerName title reviewerRatings
0 Charles Harry Potter Book Seven News:... 3.0
1 Katherine Harry Potter Boxed Set, Books... 5.0
2 Lora Harry Potter and the Sorcerer... 5.0
3 Cait Harry Potter and the Half-Blo... 5.0
4 Diane Harry Potter and the Order of... 5.0
输入:len(df['reviewerName'].unique())
输出:66130
鉴于 66130 个 unqiue 值中的每一个都有多个值(即“Charles”会出现 3 次),我将 66130 个唯一的“reviewerName”分配为 key在新的嵌套 DataFrame 中,然后使用“title”和“reviewerRatings”分配 value 作为同一嵌套 DataFrame 中的另一层 key:value。
输入:df = df.set_index(['reviewerName', 'title']).sort_index()
输出:
reviewerRatings
reviewerName title
Charles Harry Potter Book Seven News:... 3.0
Harry Potter and the Half-Blo... 3.5
Harry Potter and the Order of... 4.0
Katherine Harry Potter Boxed Set, Books... 5.0
Harry Potter and the Half-Blo... 2.5
Harry Potter and the Order of... 5.0
...
230898 rows x 1 columns
作为后续行动 first question,我尝试将嵌套的 DataFrame 转换为嵌套的 Dictionary。
上面新的嵌套 DataFrame 列索引在第一行(第 3 列)显示“reviewerRatings”,在第二行(第 1 和 2 列)显示“reviewerName”和“title”,当我运行 df.to_dict() 方法时下面,输出显示{reviewerRatingsIndexName: {(reviewerName, title): reviewerRatings}}
输入:df.to_dict()
输出:
{'reviewerRatings':
{
('Charles', 'Harry Potter Book Seven News:...'): 3.0,
('Charles', 'Harry Potter and the Half-Blo...'): 3.5,
('Charles', 'Harry Potter and the Order of...'): 4.0,
('Katherine', 'Harry Potter Boxed Set, Books...'): 5.0,
('Katherine', 'Harry Potter and the Half-Blo...'): 2.5,
('Katherine', 'Harry Potter and the Order of...'): 5.0,
...}
}
但对于下面我想要的输出,我希望得到我的输出为 {reviewerName: {title: reviewerRating}},这正是我在嵌套 DataFrame 中排序的方式。
{'Charles':
{'Harry Potter Book Seven News:...': 3.0,
'Harry Potter and the Half-Blo...': 3.5,
'Harry Potter and the Order of...': 4.0},
'Katherine':
{'Harry Potter Boxed Set, Books...': 5.0,
'Harry Potter and the Half-Blo...': 2.5,
'Harry Potter and the Order of...': 5.0},
...}
有什么方法可以操作嵌套的 DataFrame 或嵌套的 Dictionary,这样当我运行 df.to_dict() 方法时,它会显示 {reviewerName: {title: reviewerRating}}。
谢谢!
【问题讨论】:
标签: python pandas dictionary dataframe nested