0

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?

df = pd.DataFrame(columns = ['a','b','c'])
df['foo'] = 'bar'

Should yield

 a   b   c   foo
0 NaN NaN NaN bar

instead it yields

  a   b   c 
1
  • it will return an empty dataframe; Empty DataFrame Columns: [a, b, c, foo] Index: []
    – sammywemmy
    Commented Aug 30, 2021 at 21:31

1 Answer 1

1

You can use .loc specifying the row index and column label, as follows:

df.loc[0, 'foo'] = 'bar'

Result:

print(df)

     a    b    c  foo
0  NaN  NaN  NaN  bar

You can also use:

df['foo'] = ['bar']

Result:

print(df)

     a    b    c  foo
0  NaN  NaN  NaN  bar

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:

df['foo'] = ['bar'] * (df.shape[0] if df.shape[0] else 1)

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.

4
  • Nice! However, if I were running this on a bunch of dataframes and some have more than one row I want to fill, is there any way more efficient than if len(df) == 0: df.loc[0,'foo']='bar' else: df['foo'] = 'bar'
    – ACan
    Commented Aug 30, 2021 at 21:40
  • @ACan That's an interesting question! I think it depends on whether the bunch of dataframes have any common pattern which you can ride on to derive a short cut or better way for it. I don't have any sure shot and universal answer for this yet.
    – SeaBean
    Commented Aug 30, 2021 at 21:54
  • @ACan The code you proposed is a feasible way for it. At least you won't get empty dataframe without warning but found it afterwards unexpectedly.
    – SeaBean
    Commented Aug 30, 2021 at 21:58
  • @ACan See my edit above, you can use a more compact code df['foo'] = ['bar'] * (df.shape[0] if df.shape[0] else 1) for your bunch of dataframes.
    – SeaBean
    Commented Aug 30, 2021 at 22:20

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.