熊猫:以均匀间隔向索引添加元素

问题描述

我有一个如下所示的数据框:

             B
A             
0.00    5.7096
7.33    8.0280
25.82  15.7212
43.63  19.5156
55.24  20.1888

并且我想定期添加带有索引的行(比如 10),这样我就可以使用 method = 'index' 插入列 B。我想要的输出是这样的:

             B
A             
0.00    5.7096
7.33    8.0280
10.00      NaN
20.00      NaN
25.82  15.7212
30.00      NaN
40.00      NaN
43.63  19.5156
50.00      NaN
55.24  20.1888
60.00      NaN

我没有找到任何可以添加索引元素而不是更改它们的重新索引选项。我最好的解决方案是创建一个新索引,将其附加到原始数据帧,排序并删除重复项(如果有),但我很确定有更好的解决方案。

step = 10
idx = pd.DataFrame(index = df.index).reindex([round(i,0) for i in np.arange(df.index[0],df.index[-1] + step,step)])
df = df.append(idx)
df.sort_index(inplace = True)
df = df[~df.index.duplicated()]

有什么建议吗?谢谢

解决方法

通过外连接有效地进行联合。

df = pd.read_csv(io.StringIO("""A             B
0.00    5.7096
7.33    8.0280
25.82  15.7212
43.63  19.5156
55.24  20.1888"""),sep="\s+").set_index("A")

df = df.join(pd.DataFrame(index=pd.RangeIndex(0,60,10)),how="outer")

B
0 5.7096
7.33 8.028
10 nan
20 nan
25.82 15.7212
30 nan
40 nan
43.63 19.5156
50 nan
55.24 20.1888
,
idx = sorted(set(list(np.arange(70,step=10)) + list(df.index)))
df = df.reindex(idx)

输出:

df 出[59]:

             B
A             
0.00    5.7096
7.33    8.0280
10.00      NaN
20.00      NaN
25.82  15.7212
30.00      NaN
40.00      NaN
43.63  19.5156
50.00      NaN
55.24  20.1888
60.00      NaN
,

重新索引数据框怎么样?结果与您提供的解决方案相同:

lista = [0.00,7.33,25.82,43.63,55.24]
listb = [5.7096,8.0280,15.7212,19.5156,20.1888]
df = pd.DataFrame({'A':lista,'B':listb})

# range(start,stop,step)
# Create new index and increment
my_increment = [i for i in range(10,20,10)]
# combine old and new index,here is where you can use the list function to sort them as well
new_index = df.index.tolist() + my_increment

print(df.reindex(new_index))

输出:

        A        B
0    0.00   5.7096
1    7.33   8.0280
2   25.82  15.7212
3   43.63  19.5156
4   55.24  20.1888
10    NaN      NaN

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...