簡體   English   中英

替換數據框列中的特定值

[英]Replacing specific values within a dataframe column

我在jupyter筆記本中運行以下代碼,該代碼檢查nametest_df['text']的文本字符串並返回人員名稱。 我設法使此工作正常,並想將這些名稱推送到nametest_df['name']中的各個字段,其中當前所有值均為NaN

我嘗試了Series.replace()方法,但是“名稱”列中的所有條目都顯示相同的名稱。

有什么線索可以有效地做到這一點嗎?

for word in nametest_df['text']:

    for sent in nltk.sent_tokenize(word):
        tokens = nltk.tokenize.word_tokenize(sent)
        tags = st.tag(tokens)

        for tag in tags:
            if tag[1]=='PERSON':
                name = tag[0]
                print(name)

    nametest_df.name = nametest_df.name.replace({"NaN": name})

樣本名稱test_df

      **text**                    **name**
0   His name is John                NaN
1   I went to the beach             NaN
2   My friend is called Fred        NaN

預期產量

      **text**                    **name**
0   His name is John                John                
1   I went to the beach             NaN
2   My friend is called Fred        Fred      

不要嘗試一一填寫序列值。 這是低效率的,容易出錯。 一個更好的主意是創建一個名稱列表並直接分配。

L = []
for word in nametest_df['text']:
    for sent in nltk.sent_tokenize(word):
        tokens = nltk.tokenize.word_tokenize(sent)
        tags = st.tag(tokens)
        for tag in tags:
            if tag[1]=='PERSON':
                L.append(tag[0])

nametest_df.loc[nametest_df['name'].isnull(), 'name'] = L

暫無
暫無

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

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