Skip to content
Advertisement

How to rename a header and add values (to this column) based on other header name?

I have multiple Pandas dataframes like this one (for different years):

df1=

JavaScript

And I would like to assign to the nan the year in the Monthly Flow (2018) column, thus achieving this output:

JavaScript

I know how to replace these nan by a specific year, one dataframe at a time.

But, since I have a lot of dataframes (and will have more in the future), I would like to know a way to do this automatically, for example by extracting the year value from column Monthly Flow (2018).

Advertisement

Answer

Assuming Monthly flow is always the 5th column, you can do it like this:

JavaScript

Explanation:

re.search looks for 4 numbers in a row and extracts them from the fifth column.

I rename the Unnamed column as Year.

Working code:

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