简体   繁体   中英

fill pandas values dictionary using list comprehension

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?

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__()
                              )
                        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM