熊猫:使用列标题和字典中元组的单元格值创建数据框

时间:2020-04-19 02:40:18

标签: python pandas dataframe dictionary tuples

我有一个简单的pandas数据框,有两列:

document  document_topics 
0         [(0, 0.0280), (1, 0.0372), (2, 0.0131), ... (42, 0.0969)]
1 ...     [(1, 0.0829), (3, 0.0161), (4, 0.0141), ... (27, 0.2275)]

“ document_topics”列是(主题,权重)的元组。我想分割'document_topics'并得到一个像这样的数据框:

document  topic_0  topic_1  topic_2 topic_3 topic_4...
0         0.0280   0.0372   0.0131  NaN     NaN  
1 ...     NaN      0.0829   NaN     0.0161  0.0141

不是每个文档都具有与其相关的所有主题,因此我想用“ NaN”填充这些值。创建此数据框的最佳方法是什么?

3 个答案:

答案 0 :(得分:3)

您可以explode列表,然后获取元组的第一个和第二个元素以及pivot

df = df.explode('document_topics') 

df = (df.assign(topic=df.document_topics.str[0], 
                vals=df.document_topics.str[1])
        .pivot(index='document', columns='topic', values='vals'))

# Clean up names, add prefixes
df = df.add_prefix('topic_').reset_index().rename_axis(columns=None)

   document  topic_0  topic_1  topic_2  topic_3  topic_4  topic_27  topic_42
0         0    0.028   0.0372   0.0131      NaN      NaN       NaN    0.0969
1         1      NaN   0.0829      NaN   0.0161   0.0141    0.2275       NaN

答案 1 :(得分:1)

首先,您需要知道总共有total_topics个主题,然后创建一个新的列表列表,该列表中的每个元素都是一个始终包含total_topics元素的列表,如果没有,则为None它不见了。

document_topics = df.document_topics.to_list()
topics = sum(document_topics, [])
topics = set([topic[0] for topic in topics])
for i, document_topic in enumerate(document_topics):
    document_topic = dict(document_topic)
    document_topics[i] = []
    for topic in topics:
        document_topics[i].append(document_topic[topic] if topic in document_topic else None)
columns = [f'topic_{i}' for i in topics]
df_new = pd.DataFrame(data=document_topics, columns=columns)

答案 2 :(得分:0)

您可以使用transform并定义自己的函数

df = pd.DataFrame(columns=['document_topics'])
df.loc[len(df), df.columns[0]] = [(0, 0.0280),
                                (1, 0.0372), (2, 0.0131), (3, 0.0969)]

df.loc[len(df), df.columns[0]] = [(0, 0.0280), (1, 0.0280),
                            (2, 0.0372), (3, 0.0131), (42, 0.0969)]


def fun(row):
    df = pd.DataFrame(row, columns=['idx', 'vals'])
    df['idx_index'] = 'topic_' + df['idx'].astype(str)
    df.set_index('idx_index', inplace=True)
    return df['vals']


df.document_topics.transform(fun)

# topic_0   topic_1 topic_2 topic_3 topic_42
# 0 0.028   0.0372  0.0131  0.0969  NaN
# 1 0.028   0.0280  0.0372  0.0131  0.0969