Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.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 使用附加列将行转换为列_Python_Pandas_Pivot - Fatal编程技术网

Python 使用附加列将行转换为列

Python 使用附加列将行转换为列,python,pandas,pivot,Python,Pandas,Pivot,假设我有以下数据帧df: type cat val a x 3 a x1 1 a x2 3.5 b x3 7 b x4 2 c x1 8 现在,我正试图获得如下信息: type cat1 val1 cat2 val2 cat3 val3 cat4 val4 a x 3 x2 3.5 x2 7 na

假设我有以下数据帧df:

type  cat  val
a     x      3
a     x1     1
a     x2     3.5
b     x3     7
b     x4     2
c     x1     8
现在,我正试图获得如下信息:

type  cat1    val1    cat2   val2   cat3   val3   cat4   val4
a     x        3      x2     3.5     x2     7     nan    nan
b     x3       7      nan    nan     nan    nan   x4     2
c     x1       8      nan    nan     nan    nan   nan    nan
因此,基本上,我已经基于“cat”的唯一值创建了04个新列,然后将“val”相应地分配到单元格中,新表通过“type”进行索引

这对熊猫透视表会有帮助吗

提前谢谢

干杯,
Tom

我建议使用
pd.pivot\u table()

它没有像您那样的列,但它确实减少了维度和
NaN
s的数量


希望这有帮助

我建议使用
pd.pivot\u table()

它没有像您那样的列,但它确实减少了维度和
NaN
s的数量

希望这有帮助

# make dataframe
df = pd.DataFrame({'type' : ['a']*3 + ['b']*2 + ['c'],
                   'cat' : ['x', 'x1', 'x2', 'x3', 'x4', 'x1'],
                   'val' : [3, 1, 3.5, 7, 2, 8]})

# pivot
df.pivot_table(index = 'type',
               columns = 'cat',
               values = 'val')