Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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 3.x 如何在转置数据帧后合并具有相同标签的所有列?_Python 3.x_Pandas_Dataframe_Transformation - Fatal编程技术网

Python 3.x 如何在转置数据帧后合并具有相同标签的所有列?

Python 3.x 如何在转置数据帧后合并具有相同标签的所有列?,python-3.x,pandas,dataframe,transformation,Python 3.x,Pandas,Dataframe,Transformation,我有一个df,在“转置”df后看起来像这样: 1 2 3 4 5 \ level_1 questionId type value exportLabel questionId 0 participantId id -Ll4truw3KbSjVRtXmJy Viewed vi

我有一个df,在“转置”df后看起来像这样:

                     1     2                     3            4           5  \
level_1     questionId  type                 value  exportLabel  questionId   
0        participantId    id  -Ll4truw3KbSjVRtXmJy       Viewed    viewTime   

            6                         7            8  
level_1  type                     value  exportLabel  
0        time  2019-07-31T02:41:34.063Z      Started  
如果名称匹配,如何合并值
level_1
索引行,并将其放入列中

新的df应如下所示:

    questionId       type          value            exportLabel
  0  participantId    id    -Ll4truw3KbSjVRtXmJy         Viewed    
  1  viewTime         time  2019-07-31T02:41:34.063Z    Started
我尝试了
groupby
,但数据被转换回序列,索引成为列,代码如下:

df = df.groupby(df.loc['level_1'])



如果您可以发布代码以重新创建该数据帧(因为它是一个多索引),这将非常有用@anky_91您是否要求非常原始的数据帧?不,发布多索引数据帧示例时,建议发布代码以重新生成该数据帧,而不是复制数据
df (your data).. Generated using below

temp = StringIO("""  
                     1     2                     3            4           5   6          7            8  
level_1     questionId  type                 value  exportLabel  questionId  type      value  exportLabel   
0        participantId    id  -Ll4truw3KbSjVRtXmJy       Viewed    viewTime   time  2019-07-31T02:41:34.063Z      Started  

""")

df = pd.read_csv(temp, sep='\s+')
##df


                     1     2                     3            4           5  \
level_1     questionId  type                 value  exportLabel  questionId   
0        participantId    id  -Ll4truw3KbSjVRtXmJy       Viewed    viewTime   

            6                         7            8  
level_1  type                     value  exportLabel  
0        time  2019-07-31T02:41:34.063Z      Started  
df = df.T.groupby('level_1')['0'].apply(lambda x: pd.Series(list(x))).unstack().T
del df.columns.name
print(df[['questionId','type','value','exportLabel']])
      questionId  type                     value exportLabel
0  participantId    id      -Ll4truw3KbSjVRtXmJy      Viewed
1       viewTime  time  2019-07-31T02:41:34.063Z     Started