Python 我如何处理pytrends的结果?
所以我是python新手,在使用pytrends时遇到了一个问题。我正在尝试比较5个搜索词,并将总和存储在CSV中 我现在遇到的问题是,我似乎无法隔离返回的单个元素。我有数据,我可以看到它,但我似乎无法分离出一个元素来对它做任何有意义的事情 我在别处找到了一个使用iloc的建议,但它不会返回所显示的任何内容,如果我只传递一个参数,它似乎会显示所有内容 这感觉真的很傻,但我就是搞不懂,在网上也找不到任何东西Python 我如何处理pytrends的结果?,python,python-3.x,google-trends,Python,Python 3.x,Google Trends,所以我是python新手,在使用pytrends时遇到了一个问题。我正在尝试比较5个搜索词,并将总和存储在CSV中 我现在遇到的问题是,我似乎无法隔离返回的单个元素。我有数据,我可以看到它,但我似乎无法分离出一个元素来对它做任何有意义的事情 我在别处找到了一个使用iloc的建议,但它不会返回所显示的任何内容,如果我只传递一个参数,它似乎会显示所有内容 这感觉真的很傻,但我就是搞不懂,在网上也找不到任何东西 from pytrends.request import TrendReq import
from pytrends.request import TrendReq
import csv
import pandas
import numpy
import time
# Login to Google. Only need to run this once, the rest of requests will use the same session.
pytrend = TrendReq(hl='en-US', tz=360)
with open('database.csv',"r") as f:
reader = csv.reader(f,delimiter = ",")
data = list(reader)
row_count = len(data)
comparator_string = data[1][0] + " opening"
print("comparator: ",comparator_string,"\n")
#Initialize search term list including comparator_string as the first item, plus 4 search terms
kw_list=[]
kw_list.append(comparator_string)
for x in range(1, 5, 1):
search_string = data[x][0] + " opening"
kw_list.append(search_string)
# Create payload and capture API tokens. Only needed for interest_over_time(), interest_by_region() & related_queries()
pytrend.build_payload(kw_list, cat=0, timeframe='today 3-m',geo='',gprop='')
# Interest Over Time
interest_over_time_df = pytrend.interest_over_time()
#time.sleep(randint(5, 10))
#printer = interest_over_time_df.sum()
printer = interest_over_time_df.iloc[1,1]
print("printer: \n",printer)
pytrends返回对象,有很多方法可以实现
让我们以以下代码为例:
kw_list = ['apples', 'oranges', 'bananas']
interest_over_time_df = pytrend.interest_over_time()
如果运行print(兴趣随时间变化)
apples oranges bananas isPartial
date
2017-10-23 77 15 43 False
2017-10-24 77 15 46 False
2017-10-25 78 14 41 False
2017-10-26 78 14 43 False
2017-10-27 81 17 42 False
2017-10-28 91 17 39 False
...
您将在左侧看到一个索引列date
,以及四个数据列apples
、oranges
、香蕉
和isPartial
。现在可以忽略isPartial
:该字段让您知道该特定日期的数据点是否完整
此时,您可以按列、按列+索引等选择数据:
>>> interest_over_time_df['apples']
date
2017-10-23 77
2017-10-24 77
2017-10-25 78
2017-10-26 78
2017-10-27 81
>>> interest_over_time_df['apples']['2017-10-26']
78
>>> interest_over_time_df.iloc[4] # Give me row 4
apples 81
oranges 17
bananas 42
isPartial False
Name: 2017-10-27 00:00:00, dtype: object
>>> interest_over_time_df.iloc[4, 0] # Give me row 4, value 0
81
您可能感兴趣的是,按标签选择行,而不是按整数选择行:
>>> interest_over_time_df.loc['2017-10-26']
apples 78
oranges 14
bananas 43
isPartial False
Name: 2017-10-26 00:00:00, dtype: object
>>> interest_over_time_df.loc['2017-10-26', 'apples']
78
希望对您有所帮助。欢迎来到Stack Overflow!您可以先学习并创建一个示例。这使我们更容易帮助你。