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:

defget_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]:dfOut[25]:catsdogscatfooddogfoodDate2015-01-04  74.085.065.047.02015-01-11  74.084.060.052.02015-01-18  72.082.049.057.02015-01-25  69.078.045.037.02015-02-01  73.077.051.052.0...............2015-11-29  83.080.047.049.02015-12-06  80.079.070.050.02015-12-13  83.084.067.049.02015-12-20  89.091.061.058.02015-12-27  90.0100.058.045.0

[52rowsx4columns]

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

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"