简体   繁体   English

使用列表理解填充熊猫值字典

[英]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:如果loc包含所有唯一的location值,那么您只需要:

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.请注意,强烈建议在此处使用 groupby,它比使用 for 循环快得多。 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 (不是开始为空)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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