簡體   English   中英

熊貓:將數據框列合並到列表中

[英]Pandas: Merge a dataframe column to a list

我正在使用Python(Nltk,Pandas)進行一些文本分析,並且需要一些有關Dataframe的幫助。 我仍然是編程初學者。

我有一個PoS標記數據框(1000行,5列)。

列名:編號(索引中的此),ID,標題,問題,答案

#2 Example rows for Question:

[('I', 'PRON'), ('am', 'VERB'), ('working', 'VERB'),('website', 'NOUN')]
[('Would', 'VERB'), ('you', 'PRON'), ('recomme...)] 

#2 Example rows for Answers:

[('This', 'DET'), ('is', 'VERB'), ('not', 'ADV'),('website', 'NOUN')] 
[('There', 'DET'), ('is', 'VERB'), ('a', 'DET'...)] 

目標:

1.)包含所有1000個PoS標記問題的一個 列表 (非str)

2.)包含所有1000個PoS標記答案的一個 列表 (非str)

3.)包含所有1000個PoS標記的答案和問題的一個 列表 (非str)

到目前為止,我嘗試的是合並“問題”列中的所有行,但是我的結果是:

[[('I', 'PRON'), ('am', 'VERB'),..],[('Would', 'VERB'), 
('you', 'PRON'), ('recomme...)],[(.....)]]  

我想我加入他們的工作是一個錯誤。 我怎樣才能正確地做到這一點,看起來像這樣的清單:

[('I', 'PRON'), ('am', 'VERB'), ('working', 'VERB'),.....]

完整列。

Beneres回答后編輯:

謝謝您的快速解答。 .sum()是我以前做過的方法,但結果是:

print (df['Merged'])
0      [('Does', 'NOUN'), ('anyone', 'NOUN'), ('know'...
1      [('I', 'PRON'), ('am', 'VERB'), ('building', '...
2      [('I', 'PRON'), ('am', 'VERB'), ('wondering', ...
3      [('I', 'PRON'), ('am', 'VERB'), ('working', 'V...

我需要的是

print (df['Merged'])
0      [('Does', 'NOUN'), ('anyone', 'NOUN'), ('know'...
        ('I', 'PRON'), ('am', 'VERB'), ('building', '...
        ('I', 'PRON'), ('am', 'VERB'), ('wondering', ...
        ('I', 'PRON'), ('am', 'VERB'), ('working', 'V...]

編輯2:解決

如果我理解得很好,則只需執行以下操作:

df['Merged'] = df['Questions'] + df['Answers']

合並問題和答案,然后執行

df.sum()

合並(匯總)所有列表。

例:

import pandas as pd

df = pd.DataFrame({'Q':[[('I', 'PRON'), ('am', 'VERB')], [('You', 'PRON'), ('are', 'VERB')]], 
              'A':[[('This', 'DET'), ('is', 'VERB')], [('Sparta', 'NOUN'), ('bitch', 'VERB')]]})
df['Merged'] = df['A'] +df['Q']

然后:

df.sum()

看起來像這樣:

A         [(This, DET), (is, VERB), (Sparta, NOUN), (bit...
Q         [(I, PRON), (am, VERB), (You, PRON), (are, VERB)]
Merged    [(This, DET), (is, VERB), (I, PRON), (am, VERB...
dtype: object

然后,我對目標3的格式不太確定,如果這不是您想要的,請提供更多詳細信息。

我以一種怪異的方式解決了這個問題,不知道這是否是一個好的解決方案,但是它可以工作:

from ast import literal_eval

# sum all columns and replace resulting "][" between columns with ", "
# change str to list with literal_eval
allQuestions = literal_eval(dfQuestion.sum().replace("][", " ,"))
allAnswers = literal_eval(dfAnswers.sum().replace("][", " ,"))
allPosts = allQuestions + allAnswers

我希望這可以幫助其他人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM