2016-03-31 28 views
0

我在python df中有一個數據框。在一列中分割句子,然後在python中添加數據框

其結構如下: -

Sentences     | Value 
This is my house   |  0 
My house is good   |  2 

。 。 。 。

現在我想要它將列句拆分爲單詞,然後有一個熊貓數據框將這些單詞的原始句子值附加到它們前面。

輸出應該如下: -

Words | Value 
This | 0 
is | 0 
my | 0 
house | 0 
My | 2 
house | 2 
is | 2 
good | 2 

。 。 。

我已經使用了一個函數來分割句子。

def makeTermsFrom(msg): 
    return [m for m in msg.lower().split() if m] 

a = readMessagesFromFile("./data/a_labelled.txt") #Returns a df 
b = makeTermsFrom(a['Sentences'].iloc[0]) #Splits the sentences 

但我無法在df中添加單詞及其值。

回答

1

使用DataFrame.itertuples()方法:

import pandas as pd 

df = pd.DataFrame(
    [['John Lennon', 10], ['George Harrison', 6]], 
    columns=['beatle', 'songs'] 
) 

longform = pd.DataFrame(columns=['word', 'num']) 

for idx, name, songs in df.itertuples(): 
    name_words = (i.lower() for i in name.split()) 

    longform = longform.append(
     [{'word': nw, 'num': songs} for nw in name_words], 
     ignore_index=True 
    ) 

print(longform.head()) 

#  word num 
# 0  john 10 
# 1 lennon 10 
# 2 george 6 
# 3 harrison 6 
+0

工作就像一個charm.Thanks。 –

相關問題