Dataframe(pyspark)
+-----------+---+-----------+
| Name|Age|word_count |
+-----------+---+-----------+
| John | 23| 1 |
|Paul Din O.| 45| 3 |
|Kelvin Tino| 12| 2 |
+-----------+---+-----------+
预期产量:
+-----------+---+-----------+
| Name|Age|word_index |
+-----------+---+-----------+
| John | 23| 0 |
| Paul | 45| 0 |
| Din | 45| 1 |
| O. | 45| 2 |
| Kelvin | 12| 0 |
| Tino | 12| 1 |
+-----------+---+-----------+
目标:
通过拆分 name
现场。
重新索引拆分的每个块 name
. (i、 e索引将为每个 name
)
通过以下代码计算计数,
def countc(inp='', search_chars='', modifier=None):
"""
Counts the number of characters that appear or do not appear in a list of characters.
"""
# Modifier(s)
if modifier is not None:
modifier = modifier.lower()
if modifier == 'i':
# Ignore case
inp = inp.lower()
count = 0
for c in search_chars:
count += inp.count(c)
return count
udf_countc = F.udf(lambda x, y: countc(x, y), IntegerType())
# spark.udf.register('udf_countc', udf_countc)
df = df.withColumn('word_count', udf_countc(F.col('Name'), F.lit(' ')))
用下面的代码生成了重复的行。
df.withColumn('DuplicatedRow', F.expr('explode(array_repeat(name, F.col('word_count')))')).show()
如何将拆分的单词放入每个单元格并填充 index
在分裂的每一个街区 name
场?
1条答案
按热度按时间vptzau2j1#
posexplode
做你想做的事:对于您编辑的问题和评论,