change value of a column based on another column

Viewed 338

This is same question as Change one value based on another value in pandas

MRE:

df = pd.DataFrame({"id":[1,2,3,4,5,6,7],
                   "count":[3,45,123,323,4,23,7],
                   "colors":[[9,9,9], [9,9,9],
                             [9,9,9], [9,9,9], [9,9,9], [9,9,9], [9,9,9]]})

however I need to input iterable when condition is satisfied.

df.loc[df["count"] <= 30, "colors"] = "red"

works fine and it is the answer to previous question.

What I want to do is input [r, g, b] list (each value in list must be an int). note that my df has iterables in column "colors"

df.loc[df["count"] <= 30, "colors"] = [1,3,4]

gives me ValueError: Must have equal len keys and value when setting with an iterable

How can I fix this?

Expected output:

   id   count   colors
0   1   3       [1, 3, 4]
1   2   45      [9, 9, 9]
2   3   123     [9, 9, 9]
3   4   323     [9, 9, 9]
4   5   4       [1, 3, 4]
5   6   23      [1, 3, 4]
6   7   7       [1, 3, 4]

My current fix:

df.loc[df["count"] <= 30, "colors"] = "[1,3,4]"
df["color"] = df["color"].apply(lambda row: list(map(int,row.strip('][').split(","))))

This works fine however I am curious to know if there exists a simpler method like when inputting single string value.

3 Answers

Try with

df.colors = df.colors.astype(object)
df.loc[df["count"] <= 30, "colors"] = [[1,2,3]]*sum(df["count"] <= 30)

Use numpy.where here:

In [3346]: import numpy as np
In [3375]: from ast import literal_eval

In [3347]: df.colors = np.where(df['count'].le(30), '[1, 3, 4]', df.colors)

In [3380]: df.colors = df.colors.apply(lambda x: literal_eval(str(x)))

In [3348]: df
Out[3348]: 
   id  count     colors
0   1      3  [1, 3, 4]
1   2     45  [9, 9, 9]
2   3    123  [9, 9, 9]
3   4    323  [9, 9, 9]
4   5      4  [1, 3, 4]
5   6     23  [1, 3, 4]
6   7      7  [1, 3, 4]

Solution with list comprehension:

m = df["count"] <= 30
df["colors"] = [[1,3,4]  if y else x for x, y in zip(df["colors"], m)]
print (df)
   id  count     colors
0   1      3  [1, 3, 4]
1   2     45  [9, 9, 9]
2   3    123  [9, 9, 9]
3   4    323  [9, 9, 9]
4   5      4  [1, 3, 4]
5   6     23  [1, 3, 4]
6   7      7  [1, 3, 4]
Related