What’s the easiest way to add an empty column to a pandas DataFrame
object? The best I’ve stumbled upon is something like
JavaScript
x
2
1
df['foo'] = df.apply(lambda _: '', axis=1)
2
Is there a less perverse method?
Advertisement
Answer
If I understand correctly, assignment should fill:
JavaScript
1
16
16
1
>>> import numpy as np
2
>>> import pandas as pd
3
>>> df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
4
>>> df
5
A B
6
0 1 2
7
1 2 3
8
2 3 4
9
>>> df["C"] = ""
10
>>> df["D"] = np.nan
11
>>> df
12
A B C D
13
0 1 2 NaN
14
1 2 3 NaN
15
2 3 4 NaN
16