Skip to content
Advertisement

How to add an empty column to a dataframe?

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?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement