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

Python 使用dataframe列值作为列名

Python 使用dataframe列值作为列名,python,pandas,dataframe,Python,Pandas,Dataframe,我遇到一个问题。我有一个数据帧,如下所示: test_index test-item test_value Serial_Number SN_0 1 A A-0.1 SN_0 1 B B-0.1 SN_0 2 A

我遇到一个问题。我有一个数据帧,如下所示:

                  test_index test-item test_value
Serial_Number                                 
SN_0                    1         A      A-0.1
SN_0                    1         B      B-0.1
SN_0                    2         A      A-0.2
SN_0                    2         B      B-0.2
SN_1                    3         A      A-0.3
SN_1                    3         B      B-0.3
SN_1                    4         A      A-0.4
SN_1                    4         B      B-0.4
SN_3                    5         A      A-0.5
SN_3                    5         B      B-0.5
SN_3                    6         A      A-0.6
SN_3                    6         B      B-0.6
我希望获得如下所示的数据帧:

Serial_Number       test_index             A           B              
SN_0                    1               A-0.1       B-0.1
SN_0                    2               A-0.2       B-0.2
SN_1                    3               A-0.3       B-0.3
SN_1                    4               A-0.4       B-0.4
SN_3                    5               A-0.5       B-0.5
SN_3                    6               A-0.6       B-0.6

我尝试了使用
dataframe.unstack()
dataframe.reset_index()
,但失败了。

您可以使用与
append=True
参数的组合,然后。然后使用和来清理格式

注意-我认为
droplevel
是一种pandas
0.24.0
或更高版本的方法,因此这需要pandas的最新版本

(df.set_index(['test_index', 'test-item'], append=True)
 .unstack(level=2)
 .reset_index(col_level=1)
 .droplevel(0, axis=1))
[外]


对不起,各位,我喜欢这个解决方案。很多+1@anky_91谢谢你,伙计:)@user9624737没问题buddy@ChrisA,你有没有办法保持“测试项目”的顺序,谢谢。嘿@user9624737,你有没有一个例子?
test-item Serial_Number  test_index      A      B
0                  SN_0           1  A-0.1  B-0.1
1                  SN_0           2  A-0.2  B-0.2
2                  SN_1           3  A-0.3  B-0.3
3                  SN_1           4  A-0.4  B-0.4
4                  SN_3           5  A-0.5  B-0.5
5                  SN_3           6  A-0.6  B-0.6