1

I am looking to create a simple function to return two different dataframes depending on the values in a certain column.

Here's my data:

np.random.seed(1111)
df = pd.DataFrame({
'Category':np.random.choice( ['Group A','Group B','Group C','Group D'], 10000),
'Sub-Category':np.random.choice( ['X','Y','Z'], 10000),
'Sub-Category-2':np.random.choice( ['G','F','I'], 10000),
'Product':np.random.choice( ['Product 1','Product 2','Product 3'], 10000),
'Units_Sold':np.random.randint(1,100, size=(10000)),
'Dollars_Sold':np.random.randint(100,1000, size=10000),
'Customer':np.random.choice(pd.util.testing.rands_array(10,25,dtype='str'),10000),
'Date':np.random.choice( pd.date_range('1/1/2016','12/31/2018',  
                      freq='M'), 10000)})

Here's a simplified version of what I'm trying to do:

def summary(df_use):
    if df_use['Sub-Category'] == 'X':
        df1 = df_use.groupby(['Category','Sub-Category','Date']).agg({'Units_Sold':'sum'})\
            .unstack()
    elif df_use['Sub-Category'] == 'Y':
        df2 = df_use.groupby(['Category','Sub-Category','Date']).agg({'Dolars_Sold':'sum'})\
            .unstack()
    return df1, df2

I'm getting the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Any help would be greatly appreciated! I am looking to use an if statement if at all possible.

1
  • You are not looking to use an if statement. Commented Nov 8, 2019 at 0:23

1 Answer 1

1

If i understand what you are trying to do (you did not post an expected output) just remove the if statement and use boolean indexing:

def summary(df_use):
    df1 = df_use[df_use['Sub-Category'] == 'X'].groupby(['Category','Sub-Category','Date']).agg({'Units_Sold':'sum'})\
            .unstack()
    df2 = df_use[df_use['Sub-Category'] == 'Y'].groupby(['Category','Sub-Category','Date']).agg({'Dollars_Sold':'sum'})\
            .unstack()
    return df1, df2
Sign up to request clarification or add additional context in comments.

1 Comment

Wow I made that way more complicated than it needed to be. Thanks for the quick response, much appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.