Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13921

Loop in a list of dataframes

$
0
0

For now, I have this code, and it works, but I know that I can use a for loop to make the code more efficient and readable. However, I'm struggling with the implementation.

first = pd.DataFrame()second = pd.DataFrame()third = pd.DataFrame()fourth = pd.DataFrame()fiveth = pd.DataFrame()first['1PLetra'] = letrasfirst = pd.merge(first, posicao[['1PLetra', '1P']], on='1PLetra', how='left')first = first.fillna(0)second['2PLetra'] = letrassecond = pd.merge(second, posicao[['2PLetra', '2P']], on='2PLetra', how='left')second = second.fillna(0)third['3PLetra'] = letrasthird = pd.merge(third, posicao[['3PLetra', '3P']], on='3PLetra', how='left')third = third.fillna(0)fourth['4PLetra'] = letrasfourth = pd.merge(fourth, posicao[['4PLetra', '4P']], on='4PLetra', how='left')fourth = fourth.fillna(0)fiveth['5PLetra'] = letrasfiveth = pd.merge(fiveth, posicao[['5PLetra', '5P']], on='5PLetra', how='left')fiveth = fiveth.fillna(0)

I've tried the following, but with no success:

list_df = [first, second, third, fourth, fiveth]for i, df in enumerate(list_df, start=1):    col_name = f"{i}PLetra"    df[col_name] = letras    df = pd.merge(df, posicao[[col_name, f"{i}P"]], on=col_name, how='left')    df = df.fillna(0)

For anyone willing to help, I would greatly appreciate it.


Viewing all articles
Browse latest Browse all 13921

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>