Python:将功能应用到列表中 [英] Python: Applying function to list of tems

查看:459
本文介绍了Python:将功能应用到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码段,可帮助我获取Google趋势数据(请参阅 https://github.com/GeneralMills / pytrends ):

I have following code snippet that helps me to get Google Trends data (see https://github.com/GeneralMills/pytrends):

trend_payload = {'q': 'Dogs, Cats, Catfood, Dogfood','date': '01/2015 12m'}
trend = pytrend.trend(trend_payload)
df = pytrend.trend(trend_payload, return_type='dataframe')
df

由于此查询的缺点是Google趋势根据查询的数据对所有数据进行归一化,所以我更愿意让每一个调用并将df相互链接。我想到了这样的功能:

As this query has the disadvantage that Google Trends normalizes all data based on the queried data, I prefer to make each a single call and chain the df next to each other. I thought about a function like this:

queries = ['Cats', 'Dogs', 'Catfood','Dogfood']

function(queries)
    trend_payload = {'q': queries, 'date': '01/2015 12m'}
    trend = pytrend.trend(trend_payload)
    df = pytrend.trend(trend_payload, return_type='dataframe')

# then put every df of each query next to each other

我该怎么做?

推荐答案

连结DF如 jimifiki已经提出了

df = pd.concat([pytrend.trend({'q': x, 'date': '01/2015 12m'},
                              return_type='dataframe')
                for x in queries], axis=1)

或功能:

def get_trends(queries, dt):
    return pd.concat([pytrend.trend({'q': x, 'date': dt},
                                    return_type='dataframe')
                      for x in queries], axis=1)

df = get_trends(queries, '01/2015 12m')

演示:

In [24]: df = get_trends(queries, '01/2015 12m')

In [25]: df
Out[25]:
            cats   dogs  catfood  dogfood
Date
2015-01-04  74.0   85.0     65.0     47.0
2015-01-11  74.0   84.0     60.0     52.0
2015-01-18  72.0   82.0     49.0     57.0
2015-01-25  69.0   78.0     45.0     37.0
2015-02-01  73.0   77.0     51.0     52.0
...          ...    ...      ...      ...
2015-11-29  83.0   80.0     47.0     49.0
2015-12-06  80.0   79.0     70.0     50.0
2015-12-13  83.0   84.0     67.0     49.0
2015-12-20  89.0   91.0     61.0     58.0
2015-12-27  90.0  100.0     58.0     45.0

[52 rows x 4 columns]

这篇关于Python:将功能应用到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆