I am trying to pivot this dataframe photo of dataframe. I am new to pandas so I don't know why I have cells like "bake" that stretch multiple rows (this was the result of a groupby). Ideally I want "Not Math", "Could be Math", and "Math" to be column labels and the number from 'keep' in all of the cells. Please let me know if there is any easy way to do this.
Asked
Active
Viewed 20 times
0
-
Hi, please see [How to ask](https://stackoverflow.com/help/how-to-ask) and [How to create a MCVE](https://stackoverflow.com/help/mcve). For `pandas`, see [How to ask a good pandas question](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). What have you tried so far? – Evan Dec 08 '19 at 01:23
1 Answers
0
Just add reset_index, results of your groupy created a multiindex for the dataframe, to move those indexes into dataframe columns use reset_index
, secondly in your groupby method you might try and added as_index=False
as a parameter:
df = pd.DataFrame(np.random.randint(0,13,15), index =
pd.MultiIndex.from_product([['bake','bike','blocks','camera','clock'],['Could be Math','Math','Not Math']]))
df.reset_index()
Output:
level_0 level_1 0
0 bake Could be Math 2
1 bake Math 7
2 bake Not Math 5
3 bike Could be Math 12
4 bike Math 3
5 bike Not Math 7
6 blocks Could be Math 9
7 blocks Math 4
8 blocks Not Math 4
9 camera Could be Math 9
10 camera Math 7
11 camera Not Math 9
12 clock Could be Math 4
13 clock Math 10
14 clock Not Math 2

Scott Boston
- 147,308
- 15
- 139
- 187