'adding rows with Nan values to Pandas DataFrame
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 |
Solution 1:[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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
