use elements in a list for dataframe names

你离开我真会死。 提交于 2021-02-11 08:37:38

问题


I have a list like this:

network = ['facebook','organic',instagram']

And I create 3 dataframes: facebook_count, organic_count, instagram_count that each type of network.

facebook_count = df[df.isin(['facebook installs'])]
organic_count = df[df.isin(['organic installs'])]
instagram_count = df[df.isin(['instagram installs'])]

so is there a way that write a iteration that create these 3 dataframes at once? I write something like this:

for i in range(len(network)+1):
    network[i]+'_count' = df[df.isin([network[i]+' installs'])]

But it returns a SyntaxError: can't assign to operator


回答1:


The most efficient solution would be to create a dictionary storing the dataframes:

d = {i + '_count': df[df.isin([i + ' installs'])] for i in network}

And to get a dataframe, do:

print(d['facebook_count'])

Output will be the facebook_count dataframe with expected values




回答2:


An easy fix is to use dictionary

count = {}    # creating a new dictionary
for i in range(len(network)+1):
    count[network[i]+'_count'] = df[df.isin([network[i]+' installs'])]

This way, you are using the name facebook_count,organic_count and instagram_count as keys of the dictionary

i.e. count['facebook_count'] = df[df.isin('facebook installs'])]



来源:https://stackoverflow.com/questions/56217737/use-elements-in-a-list-for-dataframe-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!