Seperate out table results

Question:

I have 2 tables and I want to seperate out the combine results for AF & CA. I’m sure where I am doing wrong. How can I seperate out both the results?

   def table(df):
     mylist = ["AF", "CA"]
     for item in mylist:
       if item == 'AF':
        df.append(item)
        return()
   Table1: 
   Col1     Col 2     Col3 
    AF       98        45
    CA       10       68
   Table2:
   Col1     Col 2     Col3 
    AF       2        45
    CA       100       6

  Expected Output:
    Table for AF: 
   Col1     Col 2     Col3 
    AF       100        90
     Table for CA: 
    CA       110       74
   
  
Asked By: Josh

||

Answers:

This works for me:

df = pd.concat([df1, df2]) 
df_OUT = df.groupby('Col1', as_index=False).agg({'Col2':'sum', 'Col3':'sum'})

Output:

    Col1   Col2    Col3
0   AF     100     90
1   CA     110     74

If you want different dataframes, you can do:

df1_AF = df_OUT.loc[lambda df: df['Col1'] == 'AF']

# Output
    Col1   Col2   Col3
0   AF     100    90
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.