我正在尝试获取嵌套的数据帧并将其转换为嵌套的字典。你知道吗
这是我的原始数据帧,具有以下唯一值:
输入: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”赋值为新嵌套数据帧中的键,然后使用“title”和“reviewerRatings”作为另一层属性来指定值关键字:值相同的嵌套数据帧。你知道吗
输入: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列索引在第一行(第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}}
的形式获得我的输出,这正是我在嵌套数据帧中的排序方式。你知道吗
{'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},
...}
是否有任何方法可以操作嵌套的数据帧或嵌套的字典,以便在运行df.to_dict()
方法时,它将显示{reviewerName: {title: reviewerRating}}
。你知道吗
谢谢!你知道吗
有几种方法。可以将
groupby
与to_dict
一起使用,也可以使用collections.defaultdict
迭代行。值得注意的是,后者并不一定效率较低。你知道吗^{} +^{}
从每个
groupby
对象构造一个序列,并将其转换为字典以给出一系列字典值。最后,通过另一个to_dict
调用将其转换为字典。你知道吗^{}
定义
defaultdict
个dict
对象并逐行迭代数据帧。你知道吗结果
defaultdict
不需要转换回常规dict
,因为defaultdict
是dict
的子类。你知道吗绩效基准
基准测试是建立和数据相关的。你应该用你自己的数据来测试,看看什么最有效。你知道吗
对每个} 和lambda函数,然后输出} :
reviewerName
的dictionaries
使用^{Series
convert by ^{相关问题 更多 >
编程相关推荐