'`assign` function and strings [duplicate]
df = pd.DataFrame({"A": ["A1", "A2"], "B" : [1, 2]}
and list of strings: l = ["C", "D"]. I would like to add two columns to df as follows using assign function:
df = df.assign(l[0] = df["A"])
but I got an error "Keyword can't be an expression". What can I do?
Solution 1:[1]
You need to use a dict because l[0] is not a valid variable name:
df = df.assign(**{l[0]: df['A']})
print(df)
# Output
A B C
0 A1 1 A1
1 A2 2 A2
Solution 2:[2]
Your question is a bit vague. Is this what you want?
df[l[0]] = df["A"]
df[l[1]] = df["A"]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Corralien |
| Solution 2 | JDornheim |
