Question: I've got a matrix like this:

```
df = pd.DataFrame({'a':[7, 0, 3], 'b':[0, 4, 2], 'c':[3, 2, 9]})
df.index = list(df)
df

    a   b   c
a   7   0   3
b   0   4   2
c   3   2   9

```

And I'd like to get something like this:

```
C1  C2  V
0   a   a   7
1   a   b   0
2   a   c   3
3   b   a   0
4   b   b   4
5   b   c   2
6   c   a   3
7   c   b   2
8   c   c   9

```

For which I've written the following code:

```
vv = pd.DataFrame(columns=['C1', 'C2', 'V'])
i = 0
for cat1 in df.index:
    for cat2 in df.index:
        vv.loc[i] = [cat1, cat2, d[cat1][cat2]]
        i += 1
vv['V'] = vv['V'].astype(int)

```

Is there a better/faster/more elegant way of doing this?

Answer: 
You can use [`stack`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html):

```
df.stack()

a  a    7
   b    0
   c    3
b  a    0
   b    4
   c    2
c  a    3
   b    2
   c    9
dtype: int64

```

The `pd.set_option('display.multi_sparse', False)` will desparsen the series, showing the values in every row

Additionally, with proper renaming in a pipeline

```
df.stack()
  .reset_index()
  .rename(columns={'level_0': 'C1', 'level_1': 'C2', 0:'V'})

```

yields:

```
    C1  C2  V               
0   a   a   7
1   a   b   0
2   a   c   3
3   b   a   0
4   b   b   4
5   b   c   2
6   c   a   3
7   c   b   2
8   c   c   9

```
To complete the answer and get the same output, I've added the following code:

```
vv = df.stack().reset_index()
vv.columns = ['C1', 'C2', 'V']

```