Issue
Say I have a data frame
id col1 col2
1 1 foo
2 1 bar
And a list of column names
l = ['col3', 'col4', 'col5']
How do I add new columns to the data frame with zero as values?
id col1 col2 col3 col4 col5
1 1 foo 0 0 0
2 1 bar 0 0 0
Solution
You could try direct assignment (assuming your dataframe is named df):
for col in l:
df[col] = 0
Or use the DataFrame's assign method, which is a slightly cleaner way of doing it if l
can contain a value, an array or any pandas Series constructor.
# create a dictionary of column names and the value you want
d = dict.fromkeys(l, 0)
df.assign(**d)
Pandas Documentation on the assign
method : http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html
Answered By - Thtu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.