3

I want to insert rows with Nan values after each row

index values
0 44
1 50
2 51
3 66
4 23

DataFrame should look like this

index values
0 44
1 Nan
2 50
3 Nan
4 51
5 Nan
6 66
7 Nan
8 23

3 Answers 3

3

Use concat with DataFrame filled by NaNs and same indices and then use DataFrame.sort_index:

df = (pd.concat([df, pd.DataFrame(index=df.index)])
        .sort_index(kind='stable', ignore_index=True))
print (df)
   values
0    44.0
1     NaN
2    50.0
3     NaN
4    51.0
5     NaN
6    66.0
7     NaN
8    23.0
9     NaN

If need remove last missing value:

df = (pd.concat([df, pd.DataFrame(index=df.index)])
        .sort_index(kind='stable', ignore_index=True)
        .iloc[:-1])
print (df)
   values
0    44.0
1     NaN
2    50.0
3     NaN
4    51.0
5     NaN
6    66.0
7     NaN
8    23.0
Sign up to request clarification or add additional context in comments.

Comments

1

One option:

(df.assign(index=df['index']*2)
   .set_index('index')
   .reindex(range(len(df)*2))
   .reset_index()
)

output:

   index  values
0      0    44.0
1      1     NaN
2      2    50.0
3      3     NaN
4      4    51.0
5      5     NaN
6      6    66.0
7      7     NaN
8      8    23.0
9      9     NaN

Comments

-1
import pandas as pd
import numpy as np

df=pd.read_csv("C:\\Users\\baf03\\Downloads\\water-physical-stock-account-quarterly-1995-2020-CSV.csv")

df.loc[0,"yq"]=np.nan

df

enter image description here

1 Comment

Hello, please see meta.stackoverflow.com/editing-help Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.