Pandas Python : how to create multiple columns from a list
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001
--
Chapters
00:00 Pandas Python : How To Create Multiple Columns From A List
00:47 Accepted Answer Score 7
01:06 Answer 2 Score 7
01:35 Answer 3 Score 5
01:49 Answer 4 Score 1
02:05 Answer 5 Score 0
02:17 Thank you
--
Full question
https://stackoverflow.com/questions/5149...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001
--
Chapters
00:00 Pandas Python : How To Create Multiple Columns From A List
00:47 Accepted Answer Score 7
01:06 Answer 2 Score 7
01:35 Answer 3 Score 5
01:49 Answer 4 Score 1
02:05 Answer 5 Score 0
02:17 Thank you
--
Full question
https://stackoverflow.com/questions/5149...
--
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