How to name multiple dataframes automatically in Python?

Asked

Viewed 51 times

0

I need help automating a dataframe naming process that I’m applying. I imported 3 csv files and applied the code below, which worked smoothly:

Loja_1, Loja_2, Loja_3 = (pd.read_csv(cont) for cont in base)

I can operate the different df (Loja_1, Loja_2 and Loja_3) perfectly, that is the part of the code (pd.read_csv(cont) for cont in files) is working. However, I wish to automate the generation of the names Loja_1 to Loja_n. As it is, I have to name them manually, but the amount of df can very large, so I wish to do it automatically.

Can someone help me with this part of the code?

Grateful

  • Why don’t you use a dictionary? {Loja_1: df1, Loja_2: df2, ...}? basically would be anything like {'Loja_{}'.format(n): pd.read_csv(cont) for n, cont in enumerate(base, 1)

  • I ran the code - new={'Loja_{}'. format(n): pd.read_csv(cont) for n, cont in enumerate(base, 1)}. When I gave the type(new) command, it returned Dict (beauty). But when executing the command pd.DataFrame.from_dict(new), it returns: Valueerror: If using all scalar values, you must pass an index.

  • Why do you want to do that? You already have DF’s in DC, and to access each one of them is enough novo['Loja_1'] or novo['Loja_2'] or novo['Loja_3'] etc....

  • I needed to generate a dataframe where the name of the stores appeared in a column. So I could work with groupby. I solved the problem by reading with Glob and then running within a for read + append within a list. At the end, I made a Concat. files = Sorted(glob('Arquivos_client/*. csv')) df_intermediario = [] for file in files: df = pd.read_csv(file) df_intermediario.append(df) df_base = pd.Concat(df_intermediario, ignore_index=True)

1 answer

-2

for i in range(1, n): #sendo n o número de lojas+1
     loja ='Loja_'+str(i)
     print(loja)

I put it as print for you to test, but it’s this string + counter format that can do this task for you :)

  • Until this setting, I get enough. My problem is to link the variables generated with the respective dataframe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.