Reputation: 117
First of all, sorry for the title, but I didn't know how to put it using less than a sentence...
I have a DataFrame that looks something like:
24 36 48
A 1 2 1
B 2 2 2
C 2 1 3
And I would like to transform it to:
Num Let Val
0 24 A 1
1 24 B 2
3 24 C 2
4 36 A 2
...
n 48 C 3
The idea is to create a new column ('Let') with the values of the original df's index, and another one ('Num') with the names of the original df's columns. The 'Val' column should be the correspondent value in the original table (sort of how you would probably have a table in Excel).
The order of the rows in the new table is not relevant.
I have made some attemps with pivot_table(), but haven't been succesful.
Any idea how to go about it?
Thanks in advance!
Upvotes: 1
Views: 36
Reputation: 27
import numpy as np
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
print(f'Original Array:\n{arr1}')
arr1_transpose = arr1.transpose()
print(f'Transposed Array:\n{arr1_transpose}')
Upvotes: -1
Reputation: 336
What you are looking for is the function melt()
For your concrete example it would look something like this:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['24', '36', '48'], index=['A', 'B', 'C'])
df
# 24 36 48
# A 1 2 3
# B 4 5 6
# C 7 8 9
df.reset_index().melt(id_vars=["index"])
# index variable value
# 0 A 24 1
# 1 B 24 4
# 2 C 24 7
# 3 A 36 2
# 4 B 36 5
# 5 C 36 8
# 6 A 48 3
# 7 B 48 6
# 8 C 48 9
Upvotes: 3