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.