[英]Stacking dataframe columns (Pandas)
I am looking for a way to pivot a dataframe in reverse direction. 我正在寻找一种方法来反向旋转数据框。 To the best of my knowledge, pandas provides a pivot or pivot_table method to transform an EAV df to a "normal" one.
据我所知,pandas提供了一种pivot或pivot_table方法将EAV df转换为“普通”方法。 However, is there also a way to do the inverse?
但是,还有一种方法可以做逆运算吗?
So given the dataframe: 因此,鉴于数据帧:
$df userid ABC 0 1 1 0 1 1 3 1 2 1 5 0
I would like to transform it to (a EAV model): 我想将其转换为(EAV模型):
$df EAV
0 A 1 0 B 1 0 C 0 1 A 1 1 B 3 1 C 1 2 A 1 2 B 5 2 C 0
What would be the most efficient way to do so? 这样做最有效的方法是什么?
Assuming userid
is the index, df.stack
will do it: 假设
userid
是索引,则df.stack
将执行以下操作:
In [133]: df.stack().reset_index().rename(columns={'userid' : 'E', 'level_1' : 'A', 0 : 'V'})
Out[133]:
E A V
0 0 A 1
1 0 B 1
2 0 C 0
3 1 A 1
4 1 B 3
5 1 C 1
6 2 A 1
7 2 B 5
8 2 C 0
If userid
is not the index, set it like this: 如果
userid
不是索引,请按以下方式进行设置:
df.set_index('userid', inplace=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.