Pivoting a Pandas Dataframe containing strings – ‘No numeric types to aggregate’ error

The default aggfunc in pivot_table is np.sum and it doesn’t know what to do with strings and you haven’t indicated what the index should be properly. Trying something like: pivot_table = unified_df.pivot_table(index=[‘id’, ‘contact_id’], columns=”question”, values=”response_answer”, aggfunc=lambda x: ‘ ‘.join(x)) This explicitly sets one row per id, contact_id pair and pivots the set of response_answer values … Read more

Laravel adding data to pivot table while inserting new record

It’s really all described in the documentation. Anyway, here’s how you do it: $user = new User(); $user->username = Input::get(‘username’); $user->password = Hash::make(Input::get(‘password’)); $user->save(); $user->roles()->attach($roles); The important part is that you have to save the user before attaching (using attach()) the roles because otherwise the user doesn’t have an id yet to be used in … Read more

How can I “unpivot” specific columns from a pandas DataFrame?

This can be done with pd.melt(): # value_name is ‘value’ by default, but setting it here to make it clear pd.melt(x, id_vars=[‘farm’, ‘fruit’], var_name=”year”, value_name=”value”) Result: farm fruit year value 0 A apple 2014 10 1 B apple 2014 12 2 A pear 2014 6 3 B pear 2014 8 4 A apple 2015 11 … Read more

How do you create a “reverse pivot” in Google Sheets?

I wrote a simple general custom function, which is 100% reusable you can unpivot / reverse pivot a table of any size. In your case you could use it like this: =unpivot(A1:D4,1,1,”customer”,”sales”) So you can use it just like any built-in array function in spreadsheet. Please see here 2 examples: https://docs.google.com/spreadsheets/d/12TBoX2UI_Yu2MA2ZN3p9f-cZsySE4et1slwpgjZbSzw/edit#gid=422214765 The following is the … Read more

How is a Pandas crosstab different from a Pandas pivot_table?

The main difference between the two is the pivot_table expects your input data to already be a DataFrame; you pass a DataFrame to pivot_table and specify the index/columns/values by passing the column names as strings. With cross_tab, you don’t necessarily need to have a DataFrame going in, as you just pass array-like objects for index/columns/values. … Read more