Skip to content
Advertisement

how to add a constant column to a dataframe without rows

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

Should yield

JavaScript

instead it yields

JavaScript

Advertisement

Answer

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

JavaScript

Result:

JavaScript

You can also use:

JavaScript

Result:

JavaScript

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

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement