使用包含列表的列重塑pandas数据帧

时间:2017-07-06 19:44:05

标签: python pandas nltk

假设我有一个如下所示的数据框:

import pandas as pd

data = [{"Name" : "Project A", "Feedback" : ['we should do x', 'went well']},
            {"Name" : "Project B", "Feedback" : ['eat pop tarts', 'boo']},
            {"Name" : "Project C", "Feedback" : ['bar', 'baz']}
            ]

df = pd.DataFrame(data)
df = df[['Name','Feedback']]
df

    Name        Feedback
0   Project A   ['we should do x', 'went well']
1   Project B   ['eat pop tarts', 'boo']
2   Project C   ['bar', 'baz']

我想要做的是重塑数据框,以便Name是关键,而Feedback列列表中的每个元素都是这样的值:

        Name          Feedback
0       Project A    'we should do x'   
1       Project A    'went well'
2       Project B    'eat pop tarts'
3       Project B    'boo'
4       Project C    'bar'
5       Project C    'baz'

这样做的有效方法是什么?

2 个答案:

答案 0 :(得分:3)

一种选择是通过展平列反馈并重复列名称来重建数据框:

pd.DataFrame({
        'Name': df.Name.repeat(df.Feedback.str.len()),
        'Feedback': [x for s in df.Feedback for x in s]
    })

#         Feedback       Name
#0  we should do x  Project A
#0       went well  Project A
#1   eat pop tarts  Project B
#1             boo  Project B
#2             bar  Project C
#2             baz  Project C

答案 1 :(得分:1)

这是另一种方法:

# Separate out values (NOTE- this assumes you'll always have two strings in list)
df['pos_0'] = df['Feedback'].str[0]
df['pos_1'] = df['Feedback'].str[1]

df
        Name                     Feedback           pos_0      pos_1
0  Project A  [we should do x, went well]  we should do x  went well
1  Project B         [eat pop tarts, boo]   eat pop tarts        boo
2  Project C                   [bar, baz]             bar        baz

期望的输出:

pd.melt(df, 'Name', ['pos_0', 'pos_1'], 'Feedback').drop('Feedback', axis=1)
        Name           value
0  Project A  we should do x
1  Project B   eat pop tarts
2  Project C             bar
3  Project A       went well
4  Project B             boo
5  Project C             baz