[英]Transpose row with column instead of column with row
Can the transpose
convert data by go through the first row of all the column then only the second row of all the column, instead of go through the first column of all the row then only the second column of all the row? transpose
可以通过所有列的第一行然后仅通过所有列的第二行转换数据 go,而不是通过所有行的第一列然后仅通过所有行的第二列转换数据 go 吗?
Means require to convert the column to row which all the same data can be in one group.意味着需要将列转换为行,所有相同的数据可以在一组中。
Original data:原始数据:
columnA columnB columnC columnD columnE ...
IdA a b c d
IdB 5 6 7 8
IdC e f g h
IdD 4 5 6 7
transpose = pd.melt(id_vars = ['columnA']
,var_name = ['header']
,value_name = 'info')
Output: Output:
columnA header info
IdA columnB a
IdB columnB 5
IdC columnB e
IdD columnB 4
IdA columnC b
IdB columnC 6
IdC columnC f
IdD columnC 5
...
Expected output:预计 output:
columnA header info
IdA columnB a
IdA columnC b
IdA columnD c
IdA columnE d
IdB columnB 5
IdB columnC 6
IdB columnD 7
IdB columnE 8
...
You will need to use a stack
:您将需要使用
stack
:
out = (df.set_index('columnA').rename_axis(columns='header')
.stack(dropna=False).reset_index(name='info')
)
NB.注意。 by default,
stack
drops the NaN values, to keep them use the dropna=False
parameter.默认情况下,
stack
会丢弃 NaN 值,以使用dropna=False
参数保留它们。
Output: Output:
columnA header info
0 IdA columnB a
1 IdA columnC b
2 IdA columnD c
3 IdA columnE d
4 IdB columnB 5
5 IdB columnC 6
6 IdB columnD 7
7 IdB columnE 8
8 IdC columnB e
9 IdC columnC f
10 IdC columnD g
11 IdC columnE h
12 IdD columnB 4
13 IdD columnC 5
14 IdD columnD 6
15 IdD columnE 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.