我有一个嵌套的字典,该字典返回多个列和行作为一个值。它是通过非官方的Google Trends API获取的,下面的查询返回pandas.DataFrames字典。
# Related Queries, returns a dictionary of dataframes
related_queries_dict = pytrends.related_queries()
print(related_queries_dict)
结果:
{'jeans': {'top': query value
0 mens jeans 100
1 skinny jeans 92
2 black jeans 84
3 womens jeans 62
4 blue jeans 58
5 white jeans 55
6 ripped jeans 54
7 best jeans 42
8 levis jeans 41
9 levis 41
10 denim jeans 38
11 american eagle 37
12 american eagle jeans 36
13 levi jeans 33
14 levi 33
15 mom jeans 30
16 jeans for men 28
17 jeans for women 28
18 hollister jeans 26
19 hollister 25
20 high waisted jeans 24
21 wrangler jeans 24
22 wrangler 23
23 plus size jeans 21
24 boyfriend jeans 20, 'rising': query value
0 extreme cut jeans 6450
1 extreme cut out jeans 5800
2 skinnygirl jeans 3000
3 mugsy jeans 200
4 cut out jeans 170
5 skinny girl jeans 160
6 everlane jeans 160
7 levi mom jeans 140
8 judy blue jeans 120
9 not your daughters jeans 120
10 kancan jeans 110
11 my fit jeans 100
12 levis wedgie jeans 100
13 amiri jeans 90
14 wrangler jeans mens 90
15 mike amiri jeans 80
16 mom jeans band 80
17 wit and wisdom jeans 70
18 bell bottom jeans 60
19 how to get blood out of jeans 60
20 just my size jeans 60
21 how to get grease out of jeans 50
22 ariat jeans 50
23 ymi jeans 50
24 mr. green jeans 50}}
我想将结果分成一个熊猫数据框,所以看起来像这样:
+--------+----------------------+-------+
| Index | query | value |
+--------+----------------------+-------+
| 0 | mens jeans | 100 |
| 1 | skinny jeans | 92 |
| 2 | black jeans | 84 |
| 3 | womens jeans | 62 |
| 4 | blue jeans | 58 |
| 5 | white jeans | 55 |
| 6 | ripped jeans | 54 |
| 7 | best jeans | 42 |
| 8 | levis jeans | 41 |
| 9 | levis | 41 |
| 10 | denim jeans | 38 |
| 11 | american eagle | 37 |
| 12 | american eagle jeans | 36 |
| 13 | levi jeans | 33 |
| 14 | levi | 33 |
| 15 | mom jeans | 30 |
| 16 | jeans for men | 28 |
| 17 | jeans for women | 28 |
| 18 | hollister jeans | 26 |
| 19 | hollister | 25 |
| 20 | high waisted jeans | 24 |
| 21 | wrangler jeans | 24 |
| 22 | wrangler | 23 |
| 23 | plus size jeans | 21 |
+--------+----------------------+-------+
我已经在寻找如何将嵌套字典转换为熊猫数据框的类似答案,但是它们都不考虑分割值。
使用pd.DataFrame.from_dict将其转换为数据帧没有问题,尽管所有值都在同一行中,这给了我想要的结果:
df_new = pd.DataFrame.from_dict(related_queries_dict, orient='index')
df_new.head()
结果:
+-------+-------------------+-------------------+
| | top | rising |
+-------+-------------------+-------------------+
| jeans | query value 0 ... | query value 0 ... |
+-------+-------------------+-------------------+
答案 0 :(得分:0)
看起来“顶部”和“上升”已经是数据帧,请尝试打印呼叫以进行确认
print(type(related_queries_dict['jeans']['top']))