在“移置” 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'])
答案 0 :(得分:1)
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