[英]Python - Assign a value from one pandas df to another based on a string appearing in text
這是我的數據示例:
import pandas as pd
data = {'Text':['This is an example,',
'Another sentence is here.',
'Lets have fun.',
'this happened weeks ago.',
'I am not sure what to put here.',
'Another fake sentence.'],
'Score':[20, 21, 19, 18, 16, 12]}
# Create DataFrame
df = pd.DataFrame(data)
data_words = {'words':['is',
'fun',
'happened',
'example'],
'frequency':[127, 112, 1234, 32]}
# Create DataFrame
df2 = pd.DataFrame(data_words)
#Final Result:
data_result = {'words':['is',
'fun',
'happened',
'example'],
'frequency':[127, 112, 1234, 32],
'Text': ['This is an example,',
'Lets have fun.',
'this happened weeks ago.',
'This is an example,']}
df_final = pd.DataFrame(data_result)
我正在嘗試根據單詞是否出現在文本中將df['text']
與df2['words']
匹配。 我只需要每個單詞一個文本,理想情況下它將基於"Score"
,但這並不是完全必要的。
因此,最終的df
將包含以下列: "Text"
、 "Score"
、 "words"
和"frequency"
兩個數據框之間的簡單列表理解,並使用[0]
進行第一次出現
df2['Text'] = df2['words'].apply(lambda x: [y for y in df['Text'] if x in y][0])
output:
words frequency Text
0 is 127 This is an example,
1 fun 112 Lets have fun.
2 happened 1234 this happened weeks ago.
3 example 32 This is an example,
在解釋列表理解時,我在 "y" 中搜索 "x" 時返回值 "y",其中 x 是words
的每一行, y 是text
的每一行。 這將返回每行所有匹配項的列表。 由於多個匹配項,某些行在列表中有多個值,因此根據您的預期 output 我在末尾添加了一個[0]
以便獲取每個列表中返回的第一個值,用於逐行應用的列表理解- 行與 lambda x。 否則,如果沒有[0]
,將返回所有匹配項的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.