4

how can i select last item of list in paths column after applying the str.split("/") function?

dataNpaths = pl.scan_csv("test_data/file*.csv", has_header=True, include_file_paths = "paths").collect()
dataNpaths.with_columns(pl.col("paths").str.split("/").alias("paths"))
>>> dataNpaths.with_columns(pl.col("paths").str.split("/").alias("paths"))
shape: (30, 5)
┌──────────┬──────────┬──────────┬──────────┬────────────────────────────┐
│ Column1  ┆ Column2  ┆ Column3  ┆ Column4  ┆ paths                      │
│ ---      ┆ ---      ┆ ---      ┆ ---      ┆ ---                        │
│ f64      ┆ f64      ┆ f64      ┆ f64      ┆ list[str]                  │
╞══════════╪══════════╪══════════╪══════════╪════════════════════════════╡
│ 0.603847 ┆ 0.509877 ┆ 0.091579 ┆ 0.43821  ┆ ["test_data", "file1.csv"] │
│ 0.572299 ┆ 0.817647 ┆ 0.087951 ┆ 0.397217 ┆ ["test_data", "file1.csv"] │
│ 0.886123 ┆ 0.159805 ┆ 0.766246 ┆ 0.083915 ┆ ["test_data", "file1.csv"] │
│ 0.142208 ┆ 0.413847 ┆ 0.043408 ┆ 0.147779 ┆ ["test_data", "file1.csv"] │
│ 0.105215 ┆ 0.924754 ┆ 0.309823 ┆ 0.724407 ┆ ["test_data", "file1.csv"] │
│ …        ┆ …        ┆ …        ┆ …        ┆ …                          │
│ 0.381675 ┆ 0.849887 ┆ 0.498281 ┆ 0.733085 ┆ ["test_data", "file3.csv"] │
│ 0.697427 ┆ 0.950464 ┆ 0.999596 ┆ 0.645253 ┆ ["test_data", "file3.csv"] │
│ 0.49979  ┆ 0.172414 ┆ 0.679287 ┆ 0.091804 ┆ ["test_data", "file3.csv"] │
│ 0.668585 ┆ 0.640259 ┆ 0.932463 ┆ 0.579558 ┆ ["test_data", "file3.csv"] │
│ 0.077462 ┆ 0.802565 ┆ 0.966791 ┆ 0.29297  ┆ ["test_data", "file3.csv"] │

but neither of these approaches worked

dataNpaths.with_columns(pl.col("paths").str.split("/")[-1].alias("paths"))
dataNpaths.with_columns(pl.col("paths").str.split("/",-1).alias("paths"))

1 Answer 1

3

You should the List accessor .list which is similar to .str:

dataNpaths.with_columns(pl.col("paths").str.split("/").list[-1])

.alias('paths') is superfluous as you are using the old column name not creating a new column.

Alternatively as the last element of the List is needed, the same result can be obtained using a .list method:

dataNpaths.with_columns(pl.col("paths").str.split("/").list.last())

Details of the comprehensive .list methods are given in LINK. These include .slice, .contains, .head, .tail etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.