I am trying to add a column with a constant value to a dataframe that does not have any rows. It appears this isn’t as easy as it would be if the rows were populated. How would one accomplish this?
JavaScript
x
3
1
df = pd.DataFrame(columns = ['a','b','c'])
2
df['foo'] = 'bar'
3
Should yield
JavaScript
1
3
1
a b c foo
2
0 NaN NaN NaN bar
3
instead it yields
JavaScript
1
2
1
a b c
2
Advertisement
Answer
You can use .loc
specifying the row index and column label, as follows:
JavaScript
1
2
1
df.loc[0, 'foo'] = 'bar'
2
Result:
JavaScript
1
5
1
print(df)
2
3
a b c foo
4
0 NaN NaN NaN bar
5
You can also use:
JavaScript
1
2
1
df['foo'] = ['bar']
2
Result:
JavaScript
1
5
1
print(df)
2
3
a b c foo
4
0 NaN NaN NaN bar
5
If you have a bunch of a mix of empty and non-empty dataframes and you want to assign new column to it, you can try the following code:
JavaScript
1
2
1
df['foo'] = ['bar'] * (df.shape[0] if df.shape[0] else 1)
2
This will assign the constant with the same length (number of rows) for non-empty dataframes and will also assign one new row for empty dataframe with the constant value for the column.