在Pandas系列中删除行并清理索引

问题描述 投票:11回答:2

我有一个Pandas系列,基于一个随机数,我想选择一行(下面的代码示例中为5)并删除该行。删除行时,我想为剩余的行(0到8)创建一个新索引。代码如下:

print 'Original series: ', sample_mean_series
print 'Length of original series', len(sample_mean_series)
sample_mean_series = sample_mean_series.drop([5],axis=0)
print 'Series with item 5 dropped: ', sample_mean_series
print 'Length of modified series:', len(sample_mean_series)
print sample_mean_series.reindex(range(len(sample_mean_series)))

这是输出:

Original series:  
0    0.000074
1   -0.000067
2    0.000076
3   -0.000017
4   -0.000038
5   -0.000051
6    0.000125
7   -0.000108
8   -0.000009
9   -0.000052
Length of original series 10
Series with item 5 dropped:  
0    0.000074
1   -0.000067
2    0.000076
3   -0.000017
4   -0.000038
6    0.000125
7   -0.000108
8   -0.000009
9   -0.000052
Length of modified series: 9
0    0.000074
1   -0.000067
2    0.000076
3   -0.000017
4   -0.000038
5         NaN
6    0.000125
7   -0.000108
8   -0.000009

我的问题是第8行被删除了。我想删除行“5 NaN”并保留-0.000052,索引为0到8.这就是我想要的样子:

0    0.000074
1   -0.000067
2    0.000076
3   -0.000017
4   -0.000038
5    0.000125
6   -0.000108
7   -0.000009
8   -0.000052
python pandas series
2个回答
10
投票

有点令人困惑的是,reindex并不意味着“创造一个新的指数”。要创建新索引,只需指定index属性即可。所以在你的最后一步只做sample_mean_series.index = range(len(sample_mean_series))


10
投票

这是一个单行:

In [1]: s
Out[1]:
0   -0.942184
1    0.397485
2   -0.656745
3    1.415797
4    1.123858
5   -1.890870
6    0.401715
7   -0.193306
8   -1.018140
9    0.262998

我使用Series.drop方法删除第5行,然后使用reset_index将索引重新编号为连续。如果不使用reset_index,指数将从4跳到6而没有5。

默认情况下,reset_index会将原始索引移动到DataFrame并将其与系列值一起返回。通过drop=True防止这种情况发生。

In [2]: s2 = s.drop([5]).reset_index(drop=True)

In [3]: s2
Out[3]:
0   -0.942184
1    0.397485
2   -0.656745
3    1.415797
4    1.123858
5    0.401715
6   -0.193306
7   -1.018140
8    0.262998
Name: 0
© www.soinside.com 2019 - 2024. All rights reserved.