fill pandas values dictionary using list comprehension

92 Views Asked by At

Is there a way to replace this syntax by a list comprehension?

for w in loc:
    dict_filter_data[w] = df.loc[df['location'] == w]

If is it possible, would it be faster?

1

There are 1 best solutions below

0
On BEST ANSWER

You can do:

dict_filter_data = dict(df.loc[df['location'].isin(loc)]
                          .groupby('location').__iter__()
                       )

if loc contains all unique location values ​​then you just need:

dict_filter_data= dict(df.groupby('location').__iter__())

note that using groupby here is highly recommended, it is much faster than using a for loop. But you could do:

dict_filter_data = {w : df.loc[df['location'] == w] for w in loc}

if you want to update dict_filter_data (not start empty):

dict_filter_data.update(dict(df.loc[df['location'].isin(loc)]
                               .groupby('location').__iter__()
                            )
                       )

Or

dict_filter_data = dict(dict_filter_data, 
                        **dict(df.loc[df['location'].isin(loc)]
                                 .groupby('location').__iter__()
                              )
                        )