Python新手求助:pytrends结果提取及iloc使用问题
解决pytrends提取数据与求和存CSV的问题
嘿,作为Python新手碰到DataFrame操作的困惑太正常了,我来帮你一步步理清楚!
首先得明确:pytrends返回的interest_over_time_df是一个Pandas DataFrame,它的索引是日期,列是你设置的搜索词,最后还会自动加一列isPartial(用来标记数据是否为部分统计结果)。你用iloc[1,1]没拿到结果,大概率是对DataFrame的行列位置理解有偏差,或者没注意到这个额外的isPartial列。
第一步:先搞懂DataFrame的真实结构
先在代码里加几行调试打印,看看数据到底长什么样:
print("DataFrame的列:", interest_over_time_df.columns) print("DataFrame前5行内容:\n", interest_over_time_df.head()) print("DataFrame的行数×列数:", interest_over_time_df.shape)
这能帮你确认:
- 你设置的5个搜索词是不是都作为列存在
- 数据总共有多少行(对应多少天的统计)
isPartial列是否在末尾
第二步:正确提取单个元素
iloc是按位置索引(从0开始计数),举几个例子:
iloc[0, 0]:第一行(最早的日期)、第一列(第一个搜索词comparator_string)的热度值iloc[3, 2]:第四行、第三列的搜索词热度值
如果之前用iloc[1,1]没返回,可能是你的数据行数不足2行?或者你把isPartial列算进了列数里。用上面的打印就能明确位置。
另外,如果你想按搜索词名称提取,用loc更直观,比如:
# 提取指定日期、指定搜索词的数据 print(interest_over_time_df.loc['2024-01-01', 'your-search-term opening'])
第三步:计算总和并保存到CSV
你要的是每个搜索词的总热度,得先把isPartial列去掉(它是布尔值,求和没有意义),再用sum()方法:
# 移除isPartial列,计算各搜索词的总热度 total_interest = interest_over_time_df.drop('isPartial', axis=1).sum() # 把结果保存到CSV文件 total_interest.to_csv('search_total.csv', header=['Total Search Interest'])
生成的CSV里,每行对应一个搜索词和它的总热度值。
修改后的完整代码参考
from pytrends.request import TrendReq import csv import pandas as pd # 用pd作为pandas别名是行业通用写法,更规范 # 初始化pytrends会话 pytrend = TrendReq(hl='en-US', tz=360) with open('database.csv',"r") as f: reader = csv.reader(f, delimiter=",") data = list(reader) comparator_string = data[1][0] + " opening" print("comparator: ", comparator_string,"\n") # 构建搜索词列表(写法更简洁) kw_list = [comparator_string] for x in range(1, 5): search_string = data[x][0] + " opening" kw_list.append(search_string) # 构建请求负载 pytrend.build_payload(kw_list, cat=0, timeframe='today 3-m', geo='', gprop='') # 获取时间序列热度数据 interest_over_time_df = pytrend.interest_over_time() # 调试用:查看DataFrame结构(后续可以删掉) print("DataFrame列:", interest_over_time_df.columns) print("DataFrame形状:", interest_over_time_df.shape) # 提取单个元素示例 print("第一行第一列的热度值:", interest_over_time_df.iloc[0, 0]) # 计算总热度并保存到CSV total_interest = interest_over_time_df.drop('isPartial', axis=1).sum() total_interest.to_csv('search_total.csv', header=['Total Search Interest']) print("总热度数据已保存到search_total.csv")
按照这个思路试一下,应该就能解决你提取元素和求和存CSV的问题啦!
内容的提问来源于stack exchange,提问作者Lienne
相关产品推荐
相关产品推荐

