在pandas数据帧中删除特定条件下的其余数据



我有一个数据帧,例如:

A       B       C
27.00   9.90    6.24899992
18.00   6.90    4.827007354
15.00   4.20    2.252776065
7.50    2.90    1.673376053
3.00    3.50    3.233439065
4.00    1.20    4.254737365
3.00    2.30    1.257349325
0       8.90    0.254932365
1.00    0.90    2.233293435

现在,如果列A有0,我想把列B和C中的其余数据从前5行放到下面一行,如下所示:

A       B       C
27.00   9.90    6.24899992
18.00   6.90    4.827007354
15.00   NaN     NaN
7.50    NaN     NaN
3.00    NaN     NaN
4.00    NaN     NaN
3.00    NaN     NaN
0       NaN     NaN
1.00    NaN     NaN

我的数据帧的另一个例子:

A       B       C
27.00   9.90    6.24899992
18.00   6.90    4.827007354
15.00   4.20    2.252776065
7.50    2.90    1.673376053
3.00    NaN     NaN
4.00    NaN     NaN
3.00    NaN     NaN
2.80    NaN     NaN
1.00    NaN     NaN

我想要的结果是相同的数据,因为它在A列中没有0,如下所示:

A       B       C
27.00   9.90    6.24899992
18.00   6.90    4.827007354
15.00   4.20    2.252776065
7.50    2.90    1.673376053
3.00    NaN     NaN
4.00    NaN     NaN
3.00    NaN     NaN
2.80    NaN     NaN
1.00    NaN     NaN

我怎样才能做到这一点?

如果要在BC列中的第一个0之前设置5个值,然后在第一个0到NaN之后设置所有值,请使用:

N = 5
m = df['A'] == 0
idx = next(iter(m.index[m]), df.index[-1] + 1)
print (idx)
2
#if possible less like N rows before first 0 add max
first = max(idx - N, 0)
print (first)
7
df.iloc[first:, df.columns.get_indexer(['B','C'])] = np.nan
print (df)
A    B         C
0  27.0  9.9  6.249000
1  18.0  6.9  4.827007
2  15.0  NaN       NaN
3   7.5  NaN       NaN
4   3.0  NaN       NaN
5   4.0  NaN       NaN
6   3.0  NaN       NaN
7   0.0  NaN       NaN
8   1.0  NaN       NaN

如果列A:中没有值0

N = 5
m = df['A'] == 0
idx = next(iter(m.index[m]), df.index[-1] + 1)
print (idx)
9
#if possible less like N rows before first 0 add max
first = max(idx - N, 0)
print (first)
4
df.iloc[first:, df.columns.get_indexer(['B','C'])] = np.nan
print (df)
A    B         C
0  27.0  9.9  6.249000
1  18.0  6.9  4.827007
2  15.0  4.2  2.252776
3   7.5  2.9  1.673376
4   3.0  NaN       NaN
5   4.0  NaN       NaN
6   3.0  NaN       NaN
7  10.0  NaN       NaN
8   1.0  NaN       NaN

第一个解决方案:

#create mask
m = df['A'] == 0
#cumulative sum of mask - return Trues for all values after first 0
m1 = m.cumsum() > 0
#counter of values above 0 with swapping order by indexing [::-1] and cumulative sum
s = m.iloc[::-1].cumsum()
#create counter and compare by 5
m2 = s.groupby(s).cumcount() < 5
#chain masks by | for bitwise OR
mask = m1 | m2.sort_index()
#set NaNs by mask
df[['B','C']] = df[['B','C']].mask(mask)
print (df)

最新更新