所以我是 python 新手,在使用 pytrends 时遇到了问题。我正在尝试比较 5 个搜索词并将总和存储在 CSV 中。
我现在遇到的问题是我似乎无法隔离返回的单个元素。我有数据,我可以看到它,但我似乎无法隔离一个元素来用它做任何有意义的事情。
我在别处找到了使用 iloc 的建议,但它不会为显示的内容返回任何内容,如果我只传递一个参数,它似乎会显示所有内容。
感觉真的很蠢,但我就是想不通,也无法在网上找到任何东西。
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 返回 pandas.DataFrame
对象,并且有多种方法可以解决 indexing and selecting data .
让我们以下面的代码为例:
kw_list = ['apples', 'oranges', 'bananas']
interest_over_time_df = pytrend.interest_over_time()
如果您运行
print(interest_over_time_df)
你会看到这样的事情: 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
, bananas
, 和 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
您可能感兴趣
pandas.DataFrame.loc
,它按标签选择行,而不是 pandas.DataFrame.iloc
, 按整数选择行:>>> 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
希望有帮助。
关于python - 我如何处理 pytrends 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48246083/