Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple columns with zero values from a list to a Pandas data frame

Tags:

python

pandas

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
like image 660
arkisle Avatar asked Jan 08 '16 01:01

arkisle


People also ask

How do I add multiple columns to a Pandas DataFrame?

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.

How do I fill null values in multiple columns in pandas?

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.

How do you append a list of values to a DataFrame?

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.


1 Answers

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

like image 69
Thtu Avatar answered Sep 28 '22 12:09

Thtu