簡體   English   中英

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

[英]fill pandas values dictionary using list comprehension

有沒有辦法用列表理解替換這個語法?

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

如果可以的話,會不會更快?

你可以做:

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

如果loc包含所有唯一的location值,那么您只需要:

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

請注意,強烈建議在此處使用 groupby,它比使用 for 循環快得多。 但你可以這樣做:

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

如果你想更新dict_filter_data (不是開始為空)

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

或者

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