Remove Empty Elements from List with Character(0)

Remove empty strings from a list of strings

I would use filter:

str_list = filter(None, str_list)
str_list = filter(bool, str_list)
str_list = filter(len, str_list)
str_list = filter(lambda item: item, str_list)

Python 3 returns an iterator from filter, so should be wrapped in a call to list()

str_list = list(filter(None, str_list))

Unlist a column while retaining character(0) as empty strings in R

It's tough to say without more information about your data, but maybe this can be a solution for you, or at least point you into the right direction:

a <- list('A',character(0),'B')

> a
[[1]]
[1] "A"

[[2]]
character(0)

[[3]]
[1] "B"

> unlist(lapply(a,function(x) if(identical(x,character(0))) ' ' else x))
[1] "A" " " "B"

So in your case that should be:

df$general_RN <- unlist(lapply(df$general_RN,function(x) if(identical(x,character(0))) ' ' else x))

HTH

Removing elements with empty character in string vector

As no data is present you can try one of these options:

Option 1:

#Code1
team1_list <- as.character(team$team1[team$team1!=""])

Option 2:

#Code2
team1_list <- as.character(team$team1[levels(team$team1)!=""])

Remove empty strings in a list of lists in R

you can use lapply and simple subsetting:

x <- list(c("", "alteryx", "confirme", "", "", "", "ans", "", ""))
lapply(x, function(z){ z[!is.na(z) & z != ""]})

[[1]]
[1] "alteryx" "confirme" "ans"

lapply applies a function to every component of a list. In this case the function is a simple subsetting function.

How to remove the '' (empty string) in the list of list in python?

Try the below

final_list=[['','','','',''],['','','','','',],['country','','','',''],['','','India','','']]
lst = []
for e in final_list:
if any(e):
lst.append([x for x in e if x])
print(lst)

output

[['country'], ['India']]

Remove empty lists from a tibble in R

You can do:

df %>%
select(where(~!all(lengths(.) == 0))) %>%
mutate(z = lapply(z, function(x) ifelse(length(x) == 0, NA, x)))

# A tibble: 3 x 2
x z
<int> <list>
1 1 <chr [1]>
2 2 <chr [1]>
3 3 <lgl [1]>

Note, in your z column you can‘t have list elemtents for row 1 and 2 and a direct logical value NA. The whole column needs to be a list.

If all elements of z have only one element, you can add another line of code with mutate(z = unlist(z)).


TO asked for a more dynamic solution to pass several columns.

Here is an example where I simply created another z2 variable. Generally, you can repeat the recoding for several columns using across.

library(tidyverse)

df <- tibble(x = 1:3, y = list(as.character()),
z=list(as.character("ATC"),as.character("TAC"), as.character()),
z2 = z)

df %>%
select(where(~!all(lengths(.) == 0))) %>%
mutate(across(starts_with('z'), ~ lapply(., function(x) ifelse(length(x) == 0, NA, x))))

Which gives:

# A tibble: 3 x 3
x z z2
<int> <list> <list>
1 1 <chr [1]> <chr [1]>
2 2 <chr [1]> <chr [1]>
3 3 <lgl [1]> <lgl [1]>


Related Topics



Leave a reply



Submit