熊猫用相邻的连续值替换少于n个连续值

时间:2020-08-08 13:41:23

标签: python pandas

假设我有以下DataFrame df

df = pd.DataFrame({
"a" : [8,8,0,8,8,8,8,8,8,8,4,1,4,4,4,4,4,4,4,4,4,4,7,7,4,4,4,4,4,4,4,4,5,5,5,5,5,5,1,1,5,5,5,5,5,5,1,5,1,5,5,5,5]}

我要规范我的数据,如果连续值小于3次,则用相邻的连续值更改该值。

result:   
 df = pd.DataFrame({
        "a" : [8,8,8,8,8,8,8,8,8,8,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5]}

目前,我是通过手动迭代来完成这项工作的,并且我认为pandas具有特殊的功能。

2 个答案:

答案 0 :(得分:2)

这有点麻烦,请使用diff()cumsum()np.size来查找组的大小。使用mask()查找小于3的组,并用ffillbfill

替换
s = df.groupby((df['a'].diff() != 0).cumsum()).transform(np.size)
df['a'] = df[['a']].mask(s < 3).ffill().bfill()

#result
[8., 8., 8., 8., 8., 8., 8., 8., 8., 8., 8., 8., 4., 4., 4., 4., 4.,
   4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 4., 5., 5.,
   5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5., 5.,
   5., 5.]

答案 1 :(得分:1)

使用NumPy的作用如下:

import numpy as np
import pandas as pd

df = pd.DataFrame({"a" : [8,8,0,8,8,8,8,8,8,8,
                          4,1,4,4,4,4,4,4,4,4,
                          4,4,7,7,4,4,4,4,4,4,
                          4,4,5,5,5,5,5,5,1,1,
                          5,5,5,5,5,5,1,5,4,5,
                          5,5,5]})

arr = df.values.reshape(-1)
sub = arr[1:]-arr[:-1]
add2 = sub[1:]+sub[:-1]  
add3 = sub[2:]+sub[:-2]
del2 = np.where((sub[1:]!=0) & (add2*sub[1:]==0))[0]+1
del3 = np.where((sub[2:]!=0) & (add3*sub[2:]==0))[0]+1
arr[del2] = arr[del2-1]
arr[del3] = arr[del3-1]
arr[del3+1] = arr[del3+2]
df = pd.DataFrame({"a" : arr})
print(arr)

'''
Output:
[8 8 8 8 8 8 8 8 8 8 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5
 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5]
'''