我刚接触pyspark,我想在pyspark dataframe列中动态地用数字替换名称,因为我的dataframe中有超过500,000个名称。如何继续?
----------
| Name |
----------
| nameone|
----------
| nametwo|
----------应该变成
--------
| Name |
--------
| 1 |
--------
| 2 |
--------发布于 2019-07-25 21:33:04
你有两个我能想到的选择。如果您只有唯一的名称,您可以简单地应用monotonically_increasing_id函数。这将为每一行创建唯一但不连续的id。
import pyspark.sql.functions as F
from pyspark.ml.feature import StringIndexer
l = [
('nameone', ),
('nametwo', ),
('nameone', )
]
columns = ['Name']
df=spark.createDataFrame(l, columns)
#use Name instead of uniqueId to overwrite the column
df = df.withColumn('uniqueId', F.monotonically_increasing_id())
df.show()输出:
+-------+----------+
| Name| uniqueId|
+-------+----------+
|nameone| 0|
|nametwo|8589934592|
|nameone|8589934593|
+-------+----------+如果要将相同的id分配给具有相同Name值的行,则必须使用StringIndexer
indexer = StringIndexer(inputCol="Name", outputCol="StringINdex")
df = indexer.fit(df).transform(df)
df.show()输出:
+-------+----------+-----------+
| Name| uniqueId|StringINdex|
+-------+----------+-----------+
|nameone| 0| 0.0|
|nametwo|8589934592| 1.0|
|nameone|8589934593| 0.0|
+-------+----------+-----------+https://stackoverflow.com/questions/57195497
复制相似问题