Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert multiple consecutive columns with empty values to python dataframe

Tags:

python

pandas

I have a dataframe stations with four columns "1990", "2000", "2006", and "2012" with area data. To interpolate the years in between I want to insert columns with empty values in the gaps.

I did use pandas.DataFrame.insert to insert columns at specific locations but couldn't find out how to do that with multiple columns like pandas.DataFrame.insert[1, ["1991":"1999"], np.nan].

Is there a way to insert multiple columns with a consecutive number/name to fill the gaps? I appreciate every help!

like image 408
Benno_Banton Avatar asked Jun 27 '26 20:06

Benno_Banton


1 Answers

You won't hear this often for question about pandas, but in this instance, I think looping is probably the clearest solution:

for year in range(1991, 2000):
    df[str(year)] = np.NaN. 

You can then reorder the columns afterwards.

like image 191
Dan Avatar answered Jun 29 '26 10:06

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!