问题
Does anyone know how to transpose pandas dataframe with original row and column values? I am looping through each row and column using .iterrows() but I am sure there is a better way to do this. Maybe using pivot? Thanks!
DF looks like
a b c
0 11 12 13
1 21 22 23
2 31 32 33
I want the new DF to be
row col Val
0 0 a 11
1 0 b 12
2 0 c 13
3 1 a 21
4 1 b 22
5 1 c 23
6 2 a 31
7 2 b 32
8 2 c 33
回答1:
Here is one way using stack()
.
res = df.stack().reset_index()
res.columns = 'row col Val'.split()
res
row col Val
0 0 a 11
1 0 b 12
2 0 c 13
3 1 a 21
4 1 b 22
5 1 c 23
6 2 a 31
7 2 b 32
8 2 c 33
回答2:
You can use pandas.melt
:
>>> d
a b c
0 11 12 13
1 21 22 23
2 31 32 33
>>> pandas.melt(d.reset_index(), id_vars='index')
index variable value
0 0 a 11
1 1 a 21
2 2 a 31
3 0 b 12
4 1 b 22
5 2 b 32
6 0 c 13
7 1 c 23
8 2 c 33
The order of the values there is a bit different, but you can sort it by whatever column you like to bring things into your desired order.
回答3:
import pandas as pd
df = pd.DataFrame({'A': {0: 11, 1: 21, 2: 31},
'B': {0: 12, 1: 22, 2: 23},
'C': {0: 31, 1: 32, 2: 33}})
pd.melt(df, value_vars=['A','B','C'])
variable value
0 A 11
1 A 21
2 A 31
3 B 12
4 B 22
5 B 23
6 C 31
7 C 32
8 C 33
来源:https://stackoverflow.com/questions/32213219/pandas-dataframe-transpose-with-original-row-and-column-values