合并大熊猫

时间:2019-08-02 23:13:50

标签: python pandas

这是我的数据集。对于此问题,只需考虑第一列和最后一列。

.transform()

预期输出为:

45,37.25,14.5,-43.15,8.6
46,37.25,13.5,-42.15,8.6
47,37.25,12.5,-41.15,8.6
48,37.25,11.5,-40.15,8.6
49,37.25,10.5,-39.15,8.6
50,37.25,9.5,-38.15,8.6
51,36.25,8.5,-37.15,7.6
52,35.25,7.5,-36.15,6.6
53,34.25,6.5,-35.15,5.6
54,33.25,5.5,-34.15,4.6
55,32.25,4.5,-33.15,3.6
56,31.25,3.5,-32.15,2.6
57,30.25,2.5,-31.15,1.6
58,29.25,1.5,-30.15,0.6
59,28.25,0.5,-29.15,-0.4
60,27.25,-0.5,-28.15,-1.4
61,26.25,-0.5,-27.15,-1.4
62,25.25,-0.5,-26.15,-1.4
63,24.25,-0.5,-25.15,-1.4
64,23.25,-0.5,-24.15,-1.4
65,22.25,-0.5,-23.15,-1.4

这里的逻辑是,如果连续5行的最后一列的值相同,则中断循环并返回上面的输出。

我正在尝试以熊猫的方式解决问题,但没有任何想法开始。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

@Erfan在评论中建议,输出的第一列中可能有一个错误。

这里,假设您要保留每个组的第一行,这是一个解决方案:

# I renamed the columns
print(df)
#      a      x     y      z    b
# 0   45  37.25  14.5 -43.15  8.6
# 1   46  37.25  13.5 -42.15  8.6
# 2   47  37.25  12.5 -41.15  8.6
# 3   48  37.25  11.5 -40.15  8.6
# 4   49  37.25  10.5 -39.15  8.6
# 5   50  37.25   9.5 -38.15  8.6
# 6   51  36.25   8.5 -37.15  7.6
# 7   52  35.25   7.5 -36.15  6.6
# 8   53  34.25   6.5 -35.15  5.6
# 9   54  33.25   5.5 -34.15  4.6
# 10  55  32.25   4.5 -33.15  3.6
# 11  56  31.25   3.5 -32.15  2.6
# 12  57  30.25   2.5 -31.15  1.6
# 13  58  29.25   1.5 -30.15  0.6
# 14  59  28.25   0.5 -29.15 -0.4
# 15  60  27.25  -0.5 -28.15 -1.4
# 16  61  26.25  -0.5 -27.15 -1.4
# 17  62  25.25  -0.5 -26.15 -1.4
# 18  63  24.25  -0.5 -25.15 -1.4
# 19  64  23.25  -0.5 -24.15 -1.4
# 20  65  22.25  -0.5 -23.15 -1.4

def valid(x):
    if len(x) < 5: return x
    return x.head(1)
df["ids"] = (df.b != df.b.shift()).cumsum()

output = df.groupby("ids").apply(valid).reset_index(level=0, drop=True)[df.columns[:-1]]

print(output)
#      a      x     y      z    b
# 0   45  37.25  14.5 -43.15  8.6
# 6   51  36.25   8.5 -37.15  7.6
# 7   52  35.25   7.5 -36.15  6.6
# 8   53  34.25   6.5 -35.15  5.6
# 9   54  33.25   5.5 -34.15  4.6
# 10  55  32.25   4.5 -33.15  3.6
# 11  56  31.25   3.5 -32.15  2.6
# 12  57  30.25   2.5 -31.15  1.6
# 13  58  29.25   1.5 -30.15  0.6
# 14  59  28.25   0.5 -29.15 -0.4
# 15  60  27.25  -0.5 -28.15 -1.4

如果您想要最后一行(如果同一行中有连续5个以上的连续行),请用x.head(1)或所需的任何函数替换x.tail(1)

答案 1 :(得分:0)

这是一种方法

n=5
s1=df.iloc[:,-1].diff().ne(0).cumsum()
s2=s1.groupby(s1).transform('count')>n
pd.concat([df[s2].groupby(s1).head(1),df[~s2]]).sort_index()
     1      2     3      4    5
0   45  37.25  14.5 -43.15  8.6
6   51  36.25   8.5 -37.15  7.6
7   52  35.25   7.5 -36.15  6.6
8   53  34.25   6.5 -35.15  5.6
9   54  33.25   5.5 -34.15  4.6
10  55  32.25   4.5 -33.15  3.6
11  56  31.25   3.5 -32.15  2.6
12  57  30.25   2.5 -31.15  1.6
13  58  29.25   1.5 -30.15  0.6
14  59  28.25   0.5 -29.15 -0.4
15  60  27.25  -0.5 -28.15 -1.4