Replace grouped elements of a list

change last element in list python
servicenow grouped list
change order of list python

I have a column in a data.frame with repeated elements like:


I don't know which are the elements that are repeated because the data.frame is the result of previous calculations. For example: the repeated elements could be 3 as in this case (i.e. 7,b,c) or 4 in other cases or 2 and so on and they also could be different (i.e. 4,a,f, or 10, s, 3). I would like to replace the repeated elements with a list of colours. For example, in this case:


Or if the list is composed only by two repeated groups, the elements of the groups will be assigned to blue and yellow respectively. Is this possible? I'm able to replace elements of a list but not when I don't know how many groups are in the data.frame without to print it and table it.

Can anyone help me please?

Thank you in advance

We can use factors:


df <- data.frame(col1=c('7','7','7','7','7','b','b','b','c','c','c','c','c'),stringsAsFactors = F)
repl<- c("blue","yellow","red","purple")


df$col1 <- factor(df$col1)
levels(df$col1) <- repl
df$col1 <- as.character(df$col1) # optional, if you want character and not factor
#      col1
# 1    blue
# 2    blue
# 3    blue
# 4    blue
# 5    blue
# 6  yellow
# 7  yellow
# 8  yellow
# 9     red
# 10    red
# 11    red
# 12    red
# 13    red

Python, This article deals with binary nested list and group each nested list element Python | Replace elements in second list with index of same element in first list  It is supposed to replace the element of Index = 'Index' of the list of lists. Although it replaces on every sublist of the board. – GRoutar Nov 3 '14 at 19:11

# 1. create the data frame with the column
df <- data.frame(mycol = c(rep("7",5), rep("b", 3), rep("c", 5)), stringsAsFactors = FALSE)
# stringsAsFactors = FALSE makes the strings not to convert to Factor type
# one of the super annoying default behaviour of base-r


1      7
2      7
3      7
4      7
5      7
6      b
7      b
8      b
9      c
10     c
11     c
12     c
13     c

# 2. create a translation vector
colors <- c("7" = 'blue', "b" = "yellow", "c" = "red")
# or like this: colors <- c("blue", "yellow", "red")
# and then    : names(colors) <- c("7", "b", "c")

# 3. replace the column value according to translation vector
df$mycol <- colors[df$mycol]
# this is cool in R: The vectorization - no for loops or such needed in this case
# use the vectorization!

1    blue
2    blue
3    blue
4    blue
5    blue
6  yellow
7  yellow
8  yellow
9     red
10    red
11    red
12    red
13    red

Java Collections Utility Examples for Changing Order and Content of , Changing the order of list elements. The functions in this group allow us to reverse, rotate, permute, sort and swap elements in a list. Reverse  Python | Grouping similar substrings in list. Sometimes we have an application in which we require to group common prefix strings into one such that further processing can be done according to the grouping. This type of grouping is useful in the cases of Machine Learning and Web Development. Let’s discuss certain ways in which this can be done.

I think that this may help your need.

 recode(x, "'7'='blue'; 'b'='yellow'; 'c'='red'")

Python: Replace the last element in a list with another list, Python Exercises, Practice and Solution: Write a Python program to replace the last element in a list with another list. Learn to update or replace existing element in ArrayList with a given new element or value, using set (int index, Object element) method. To replace an existing element, we must find the exact position (index) of the element in arraylist. Once we have the index, we can use set () method to update the replace the old element with new element.

One can use both dplyr package and data.table::rleid function together to get a solution which will work with dplyr-chain.

Suppose the color vector of preference that should contain maximum number of possible color occurrence is:

myColor = c("blue", "yellow", "red", "black", "pink")

Otherwise once even use colors(distinct = TRUE) instead of myColor.

Option#1: A solution can be achieved as:


df %>% mutate(Color = myColor[rleid(Col)])

#OR -- If someone doesnt want to use `data.table` then solution can be as
df %>% mutate(Color = myColor[cumsum(Col != lag(Col, default = ""))])

#    Col  Color
# 1    7   blue
# 2    7   blue
# 3    7   blue
# 4    7   blue
# 5    7   blue
# 6    b yellow
# 7    b yellow
# 8    b yellow
# 9    c    red
# 10   c    red
# 11   c    red
# 12   c    red
# 13   c    red

Option#2: Using colors(distinct = TRUE)

df %>% mutate(Color = colors(distinct = TRUE)[cumsum(Col != lag(Col, default = ""))])
#    Col        Color
# 1    7        white
# 2    7        white
# 3    7        white
# 4    7        white
# 5    7        white
# 6    b    aliceblue
# 7    b    aliceblue
# 8    b    aliceblue
# 9    c antiquewhite
# 10   c antiquewhite
# 11   c antiquewhite
# 12   c antiquewhite
# 13   c antiquewhite


df <- read.table(text = 
stringsAsFactors = FALSE, header = TRUE)

Grouped lists, Grouping aggregates a list by a field and displays the record count per group. The total number of items in the list (all groups combined) appears near the paging In the grouped by list view, you can change the grouped list focus, hide the  Approach #2 : Pythonic Naive This is another naive approach, but more pythonic.For every inner list, it returns the i th position (which is its ordinal number) and then multiplies it with the length of that particular inner list in order to return the desired output.

Grouping data: the GroupBy() Method, So far, we have worked mostly with lists of data. We have sorted it, limited it and shaped it into new objects, but one important operation is still missing: Grouping​  You can also remove all the elements from the Python list. There is various function available in Python to delete or remove list elements in Python. These functions are remove (), del (), pop () and clear (). The explanations of these functions are given below with simple examples.

9. Lists, The syntax for accessing the elements of a list is the same as the syntax for Unlike strings, lists are mutable, which means we can change their elements. To replace easily all 1 with 10 in a = [1,2,3,4,5,1,2,3,4,5,1] one could use lambda+map combo, and 'Look, Ma, no IFs or FORs!' : # This substitutes all '1' with '10' in list 'a' and places result in list 'c':

Rearranging & Restructuring Lists, Union, Tally — enumerate, tally all distinct elements in a list. DeleteDuplicates — delete matching a pattern. SequenceReplace — replace sequences in a list  After it gets the required element, the code updates the elements of the list with the newly assigned element. Replace Old Item With New in List Within Range Using Python. You can change or update list element within full range or limited range. The full range may replace all the matching elements of the list. It may replace more than the one

  • the simplest and more robust!
  • Wow!Exactly what I need! Thank you very much!
  • It is not exactly what I need. I don't to print the df and manually set colors <- c("7" = 'blue', "b" = "yellow", "c" = "red") because the piece of code will be in a pipeline. I would like that it recognises the replicated and replaces it with color code.
  • But in the comment below this line I showed you how to do it in another way - to not to have to do colors <- c("7" = 'blue', "b" = "yellow", "c" = "red"). And it recognizes the replicates automatically - is just it looks incredibly simple - because of the vectorization.
  • Not exactly since I don't know every time which are the repeated elements.
  • So you don't know the codename for the color from the previous table?
  • then you can do one checkup before that and use unique(x) function to find out, how many groups there are, and based on the result, assign the values with recode.
  • Okkk Daglina. Thank you very much!