【发布时间】:2022-11-10 14:39:53
【问题描述】:
我想在每行之后插入带有 Nan 值的行
| index | values |
|---|---|
| 0 | 44 |
| 1 | 50 |
| 2 | 51 |
| 3 | 66 |
| 4 | 23 |
DataFrame 应该是这样的
| index | values |
|---|---|
| 0 | 44 |
| 1 | Nan |
| 2 | 50 |
| 3 | Nan |
| 4 | 51 |
| 5 | Nan |
| 6 | 66 |
| 7 | Nan |
| 8 | 23 |
【问题讨论】:
标签: python pandas dataframe rows nan
我想在每行之后插入带有 Nan 值的行
| index | values |
|---|---|
| 0 | 44 |
| 1 | 50 |
| 2 | 51 |
| 3 | 66 |
| 4 | 23 |
DataFrame 应该是这样的
| index | values |
|---|---|
| 0 | 44 |
| 1 | Nan |
| 2 | 50 |
| 3 | Nan |
| 4 | 51 |
| 5 | Nan |
| 6 | 66 |
| 7 | Nan |
| 8 | 23 |
【问题讨论】:
标签: python pandas dataframe rows nan
使用concat 和由NaNs 填充的DataFrame 和相同的索引,然后使用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
如果需要删除最后一个缺失值:
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
【讨论】:
一种选择:
(df.assign(index=df['index']*2)
.set_index('index')
.reindex(range(len(df)*2))
.reset_index()
)
输出:
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
【讨论】:
将熊猫导入为 pd 将 numpy 导入为 np
df=pd.read_csv("C:Usersaf03Downloadswater-physical-stock-account-quarterly-1995-2020-CSV.csv")
df.loc[0,"yq"]=np.nan enter image description here df
【讨论】: