Pandas Python : how to create multiple columns from a list
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Beneath the City Looping
--
Chapters
00:00 Question
00:59 Accepted answer (Score 7)
01:17 Answer 2 (Score 6)
01:50 Answer 3 (Score 4)
02:05 Answer 4 (Score 1)
02:20 Thank you
--
Full question
https://stackoverflow.com/questions/5149...
Question links:
[Add multiple empty columns to pandas DataFrame]: https://stackoverflow.com/questions/3092...
Accepted answer links:
[here]: https://stackoverflow.com/questions/3092...
Answer 2 links:
[assign]: http://pandas.pydata.org/pandas-docs/sta...
Answer 4 links:
[assign]: https://pandas.pydata.org/pandas-docs/st...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe
#avk47
    --
Music by Eric Matyas
https://www.soundimage.org
Track title: Beneath the City Looping
--
Chapters
00:00 Question
00:59 Accepted answer (Score 7)
01:17 Answer 2 (Score 6)
01:50 Answer 3 (Score 4)
02:05 Answer 4 (Score 1)
02:20 Thank you
--
Full question
https://stackoverflow.com/questions/5149...
Question links:
[Add multiple empty columns to pandas DataFrame]: https://stackoverflow.com/questions/3092...
Accepted answer links:
[here]: https://stackoverflow.com/questions/3092...
Answer 2 links:
[assign]: http://pandas.pydata.org/pandas-docs/sta...
Answer 4 links:
[assign]: https://pandas.pydata.org/pandas-docs/st...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe
#avk47
ACCEPTED ANSWER
Score 7
You need to add the columns one by one.
for col in new_cols:
    df[col] = 0
Also see the answers in here for other methods.
ANSWER 2
Score 7
Use assign by dictionary:
df = pd.DataFrame({
    'A': ['a','a','a','a','b','b','b','c','d'],
    'B': list(range(9))
})
print (df)
0  a  0
1  a  1
2  a  2
3  a  3
4  b  4
5  b  5
6  b  6
7  c  7
8  d  8
new_cols = ['new_1', 'new_2', 'new_3']
df = df.assign(**dict.fromkeys(new_cols, 0))
print (df)
   A  B  new_1  new_2  new_3
0  a  0      0      0      0
1  a  1      0      0      0
2  a  2      0      0      0
3  a  3      0      0      0
4  b  4      0      0      0
5  b  5      0      0      0
6  b  6      0      0      0
7  c  7      0      0      0
8  d  8      0      0      0
ANSWER 3
Score 1
You can use assign:
new_cols = ['new_1', 'new_2', 'new_3']
values = [0, 0, 0]   # could be anything, also pd.Series
df = df.assign(**dict(zip(new_cols, values)
ANSWER 4
Score 0
Try looping through the column names before creating the column:
for col in new_cols:
    df[col] = 0