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
Add multiple columns to a data frame using Dataframe. assign() method. Using DataFrame. assign() method, we can set column names as parameters and pass values as list to replace/create the columns.
Example 1: Filling missing columns values with fixed values: We can use fillna() function to impute the missing values of a data frame to every column defined by a dictionary of values.
Using loc[] to Append The New List to a DataFrame. By using df. loc[index]=list you can append a list as a row to the DataFrame at a specified Index, In order to add at the end get the index of the last record using len(df) function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With