Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an empty column to a dataframe?

Tags:

python

pandas

What's the easiest way to add an empty column to a pandas DataFrame object? The best I've stumbled upon is something like

df['foo'] = df.apply(lambda _: '', axis=1) 

Is there a less perverse method?

like image 471
kjo Avatar asked May 01 '13 21:05

kjo


People also ask

How do I add an empty column to a DataFrame?

Add an Empty Column by Index Using Dataframe.Use DataFrame. insert() method to add an empty column at any position on the pandas DataFrame. This adds a column inplace on the existing DataFrame object.

How do I add NaN columns in pandas?

Numpy library is used to import NaN value and use its functionality. Method 2: Using Dataframe. reindex(). This method is used to create new columns in a dataframe and assign value to these columns(if not assigned, null will be assigned automatically).

How do I add a column to a DataFrame?

You can use the assign() function to add a new column to the end of a pandas DataFrame: df = df. assign(col_name=[value1, value2, value3, ...])

How do I add columns to a DataFrame in Python?

In pandas you can add/append a new column to the existing DataFrame using DataFrame. insert() method, this method updates the existing DataFrame with a new column. DataFrame. assign() is also used to insert a new column however, this method returns a new Dataframe after adding a new column.


1 Answers

If I understand correctly, assignment should fill:

>>> import numpy as np >>> import pandas as pd >>> df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]}) >>> df    A  B 0  1  2 1  2  3 2  3  4 >>> df["C"] = "" >>> df["D"] = np.nan >>> df    A  B C   D 0  1  2   NaN 1  2  3   NaN 2  3  4   NaN 
like image 198
DSM Avatar answered Oct 10 '22 10:10

DSM