嗨,我有 2 列的数据框:
+----------------------------------------+----------+
| Text | Key_word |
+----------------------------------------+----------+
| First random text tree cheese cat | tree |
| Second random text apple pie three | text |
| Third random text burger food brain | brain |
| Fourth random text nothing thing chips | random |
+----------------------------------------+----------+
我想生成第三列,其中一个单词出现在文本中的 key_word 之前。
+----------------------------------------+----------+-------------------+--+
| Text | Key_word | word_bef_key_word | |
+----------------------------------------+----------+-------------------+--+
| First random text tree cheese cat | tree | text | |
| Second random text apple pie three | text | random | |
| Third random text burger food brain | brain | food | |
| Fourth random text nothing thing chips | random | Fourth | |
+----------------------------------------+----------+-------------------+--+
我试过这个,但它不工作
df2=df1.withColumn('word_bef_key_word',regexp_extract(df1.Text,('\\w+)'df1.key_word,1))
这是创建数据框示例的代码
df = sqlCtx.createDataFrame(
[
('First random text tree cheese cat' , 'tree'),
('Second random text apple pie three', 'text'),
('Third random text burger food brain' , 'brain'),
('Fourth random text nothing thing chips', 'random')
],
('Text', 'Key_word')
)