簡體   English   中英

在列中拆分句子,然后在python中追加數據框

[英]Splitting sentences in a column and then appending in a data frame in python

我在python df中有一個數據框。

其結構如下:

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

現在我想要將列句子拆分為單詞,然后有一個pandas數據框將這些單詞附加在其前面的原始句子值。

輸出應如下所示:

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中添加帶有其值的單詞。

使用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

暫無
暫無

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

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