Skip to content Skip to sidebar Skip to footer

Python: Applying Function To List Of Tems

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': '

Solution 1:

I would simply concatenate DFs as jimifiki has already proposed:

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

or in function:

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')

Demo:

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]

Solution 2:

You can work on this:

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

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

list_of_df = [function([query,]) for query in queries] 

then you have to concat the data frames in the list.

More elegantly you can call:

list_of_df = map(function, queries)

in this case you should rewrite function so that it accepts a single item. If you don't want to modify function you can write this:

list_of_df = map(lambda x: function([x,]), queries) 

Post a Comment for "Python: Applying Function To List Of Tems"