Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.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 使用Pandas将多行转换为一行_Python_Pandas_Dataframe_Rows - Fatal编程技术网

Python 使用Pandas将多行转换为一行

Python 使用Pandas将多行转换为一行,python,pandas,dataframe,rows,Python,Pandas,Dataframe,Rows,我相信这很容易做到,但我想不出来。 我正在用python编写代码,并使用pandas处理数据帧。我的数据框如下所示: a b c 1 10 20 1 30 40 1 60 70 1 80 100 2 10 20 2 60 70 2 80 100 我想把它变成这样: a b1 c1 b2 c2 b3 c3 b4 c4 1 10 20 30 40 60 70 80 100 2 10 20 60 70 80 100 NA NA 基本上,对于a中的值相同的每一行,取b和c中的值,并将它们转换为新列

我相信这很容易做到,但我想不出来。 我正在用python编写代码,并使用pandas处理数据帧。我的数据框如下所示:

a b  c
1 10 20
1 30 40
1 60 70
1 80 100
2 10 20
2 60 70
2 80 100
我想把它变成这样:

a b1 c1 b2 c2 b3 c3 b4 c4
1 10 20 30 40 60 70 80 100
2 10 20 60 70 80 100 NA NA
基本上,对于
a
中的值相同的每一行,取
b
c
中的值,并将它们转换为新列,这样
a
中的每个值就只有一行了

我希望我足够清楚,如果不是的话,请毫不犹豫地告诉我。 提前感谢您提供的任何帮助


Florian。

我们需要使用
cumcount

s=df.assign(key=df.groupby('a').cumcount()+1).set_index(['a','key']).stack().unstack([1,2])
s.columns=s.columns.map('{0[1]}{0[0]}'.format)
s
Out[396]: 
     b1    c1    b2    c2    b3     c3    b4     c4
a                                                  
1  10.0  20.0  30.0  40.0  60.0   70.0  80.0  100.0
2  10.0  20.0  60.0  70.0  80.0  100.0   NaN    NaN