我有一个df
包含字符串列表的数据框,如下所示:
+-------------+
Products
+-------------+
| Z9L57.W3|
| H9L23.05|
| PRL57.AF|
+-------------+
我想在 '.' 之后截断列表。字符使其看起来像:
+--------------+
Products_trunc
+--------------+
| Z9L57 |
| H9L23 |
| PRL57 |
+--------------+
我尝试使用 split 函数,但它仅适用于单个字符串而不适用于列表。我也试过
df['Products_trunc'] = df['Products'].str.split('.').str[0]
但我收到以下错误:
类型错误:“列”对象不可调用
有没有人对此有任何见解?谢谢你
如果您习惯了熊猫,您的代码看起来很像。pyspark 中的截断有点不同。看看下面:
from pyspark.sql import functions as F
l = [
( 'Z9L57.W3' , ),
( 'H9L23.05' ,),
( 'PRL57.AF' ,)
]
columns = ['Products']
df=spark.createDataFrame(l, columns)
该withColumn功能可以修改现有列或创建新的。该函数采用 2 个参数:column name
和columne expression
。当列名已经存在时,您将修改列。
df = df.withColumn('Products', F.split(df.Products, '\.').getItem(0))
df.show()
输出:
+--------+
|Products|
+--------+
| Z9L57|
| H9L23|
| PRL57|
+--------+
当您选择一个不存在的列名称时,您将创建一个新列。
df = df.withColumn('Products_trunc', F.split(df.Products, '\.').getItem(0))
df.show()
输出:
+--------+--------------+
|Products|Products_trunc|
+--------+--------------+
|Z9L57.W3| Z9L57|
|H9L23.05| H9L23|
|PRL57.AF| PRL57|
+--------+--------------+
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句