Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python dataframe:将列转换为单个列的行_Python_Pandas_Dataframe_Pivot Table - Fatal编程技术网

Python dataframe:将列转换为单个列的行

Python dataframe:将列转换为单个列的行,python,pandas,dataframe,pivot-table,Python,Pandas,Dataframe,Pivot Table,我有一个看起来像 userId feature1 feature2 feature3 ... 123456 0 0.45 0 ... 234567 0 0 0 ... 345678 0.6 0 0.2 ... . . 这些特征大部分是零,但偶尔其中一些会有非零值。一个userId的一行可以有零个、一个或多个非零特性 我想将其转换为以下数据集: user

我有一个看起来像

userId  feature1  feature2  feature3  ...
123456  0         0.45      0         ...
234567  0         0         0         ...
345678  0.6       0         0.2       ...
.
.
这些特征大部分是零,但偶尔其中一些会有非零值。一个userId的一行可以有零个、一个或多个非零特性

我想将其转换为以下数据集:

userId  feature  value
123456  feature2 0.45
345678  feature1 0.6
345678  feature3 0.2
本质上,我们只保留每个用户ID的非零特性。因此,对于用户ID 345678,我们在转换的数据集中有两行,一行用于feature1,另一行用于feature3。用户标识234567被删除,因为没有任何功能是非零的

这是否可以使用groupby或pivoting来完成?如果是,怎么做


还有其他熊猫话筒解决方案吗?

Magic from
melt

df.melt('userId').query('value!=0')
Out[459]: 
   userId  variable  value
2  345678  feature1   0.60
3  123456  feature2   0.45
8  345678  feature3   0.20
请注意,使用
stack
时,需要将掩码0设置为
NaN

df.mask(df.eq(0)).set_index('userId').stack().reset_index()
Out[460]: 
   userId   level_1     0
0  123456  feature2  0.45
1  345678  feature1  0.60
2  345678  feature3  0.20

这确实是一种魔力。这个操作是否有一个通用名称,比如说数据透视是表格数据的标准操作?@Nik这是重塑,比如熔化和堆叠——取消Pivots