0
I’m new to pandas and I’m having a hard time. I need to filter the columns in my dataframe, check if they are in a defined list and, if they are, group the columns and add up the values. It sounds simple, but I’m having a really hard time. The first image was how I tried to do it, but it went wrong. The second is my dataframe and the third is my list that I need to filter and return the sum of the columns within this list. Thanks in advance!
import pandas as pd
df = pd.read_csv(patch + 'PARTNER_23022021002403838.csv',sep=',',encoding='utf-8')
df = df.pivot_table('Value',df.index,['Flow','Country'])
df.columns = df.columns.droplevel(0)
grupos = {'Mundo' : ['Australia', 'Austria', 'Belgium', 'Canada', 'Chile', 'Czech Republic',
'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece',
'Hungary', 'Iceland', 'Ireland', 'Israel', 'Italy', 'Japan', 'Korea',
'Luxembourg', 'Mexico', 'Netherlands', 'New Zealand', 'Norway',
'Poland', 'Portugal', 'Slovak Republic', 'Slovenia', 'Spain', 'Sweden',
'Switzerland', 'Turkey', 'United Kingdom', 'United States', 'Australia',
'Austria', 'Belgium', 'Canada', 'Chile', 'Czech Republic', 'Denmark',
'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary',
'Iceland', 'Ireland', 'Israel', 'Italy', 'Japan', 'Korea', 'Luxembourg',
'Mexico', 'Netherlands', 'New Zealand', 'Norway', 'Poland', 'Portugal',
'Slovak Republic', 'Slovenia', 'Spain', 'Sweden', 'Switzerland',
'Turkey', 'United Kingdom', 'United States'],
'Desenvolvidos' : ['United Kingdom', 'United States', 'Canada', 'Japan', 'Norway', 'Switzerland' ],
'America Latina' : ['Chile','Mexico']}
paises = []
df_fim = pd.DataFrame()
for item in df.columns:
if item in grupos['Mundo']:
paises.append(item)
df_resultado = df.loc[:,paises].sum(axis=1)
df_fim = pd.concat([df_fim,df_resultado],axis=0)
df_fim.rename(columns = {'0':'B'},inplace=True)
else:
print('erro')
João Victor, instead of code images enter the code itself in the question, there is a block for indentation. Also put the dataset for testing if possible for people who will try to help you. Hug!
– lmonferrari
Thanks for the help, I’m new here
– Joao Victor