Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.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 - Fatal编程技术网

Python 将DataFrame中的每个唯一值重塑为列

Python 将DataFrame中的每个唯一值重塑为列,python,pandas,Python,Pandas,我有一个与此类似的数据帧: 12 11 10 1 a b a 2 c c a 3 c b b 4 b a a 我想为DataFrame中的每个唯一值创建一列,并将这些列作为值,如: a b c 1 [12,10] [11] NaN 2 [10] NaN [12,11] 3 NaN [11,10] [12] 4 [11,10] [12] NaN

我有一个与此类似的数据帧:

  12 11 10
1  a  b  a
2  c  c  a
3  c  b  b
4  b  a  a
我想为DataFrame中的每个唯一值创建一列,并将这些列作为值,如:

         a        b        c
1  [12,10]     [11]      NaN
2     [10]      NaN  [12,11]
3      NaN  [11,10]     [12]
4  [11,10]     [12]      NaN
您可以通过以下方式重塑,将
多索引
转换为列,然后使用聚合
列表
,最后通过以下方式删除索引和列名称:

或者将索引转换为列,以便它可以使用,然后使用与前面相同的步骤:

df1 = (df.reset_index()
         .melt('index')
         .groupby(['index','value'])['variable']
         .apply(list)
         .unstack()
         .rename_axis(index=None, columns=None))
print (df1)
          a         b         c
1  [12, 10]      [11]       NaN
2      [10]       NaN  [12, 11]
3       NaN  [11, 10]      [12]
4  [11, 10]      [12]       NaN
您可以通过以下方式重塑,将
多索引
转换为列,然后使用聚合
列表
,最后通过以下方式删除索引和列名称:

或者将索引转换为列,以便它可以使用,然后使用与前面相同的步骤:

df1 = (df.reset_index()
         .melt('index')
         .groupby(['index','value'])['variable']
         .apply(list)
         .unstack()
         .rename_axis(index=None, columns=None))
print (df1)
          a         b         c
1  [12, 10]      [11]       NaN
2      [10]       NaN  [12, 11]
3       NaN  [11, 10]      [12]
4  [11, 10]      [12]       NaN