我有大量的路径列,我需要分成2列,即basename和dirname。我知道如何使用以下命令轻松获取路径的基本名称:
val df = Seq("/test/coucou/jambon/hello/file"
,"/test/jambon/test")
.toDF("column1")
df.withColumn("basename", substring_index($"column1" , "/", -1))
.show(2, false)
+------------------------------+---------+
|column1 |basename |
+------------------------------+---------+
|/test/coucou/jambon/hello/file|file |
|/test/jambon/test |test |
+------------------------------+---------+
但是我正在努力获得这样的目录名:
+------------------------------+--------------------------+
|column1 |dirname |
+------------------------------+--------------------------+
|/test/coucou/jambon/hello/file|/test/coucou/jambon/hello |
|/test/jambon/test |/test/jambon |
+------------------------------+--------------------------+
我尝试了各种解决方案,但是找不到功能性的柱状解决方案。
我最好的办法是将减$"basename"
到$"column1"
,但我无法找到一个方法来减去字符串中的火花。
您可以使用expr对column1进行子字符串化。该代码应如下所示。希望对您有所帮助。
//Creating Test Data
val df = Seq("/test/coucou/jambon/hello/file"
,"/test/jambon/prout/test")
.toDF("column1")
val test = df.withColumn("basename", substring_index($"column1" , "/", -1))
.withColumn("path", expr("substring(column1, 1, length(column1)-length(basename)-1)"))
test.show(false)
+------------------------------+--------+-------------------------+
|column1 |basename|path |
+------------------------------+--------+-------------------------+
|/test/coucou/jambon/hello/file|file |/test/coucou/jambon/hello|
|/test/jambon/prout/test |test |/test/jambon/prout |
+------------------------------+--------+-------------------------+
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句