kjo kjo - 5 months ago 158
Python Question

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?

DSM DSM
Answer

IIUC, assignment should fill:

>>> 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
Comments