简体   繁体   English

使用新的最大值对列中的值组重新排序

[英]Reorder groups of values in the column with a new maximum value

I have a Pandas dataframe with a column with groups of digits placed in ascending order:我有一个 Pandas 数据框,其中有一列按升序排列的数字组:

column
1
2
3
4
5
6
0
1
2
3
4
1
2
3
4
5
0
0

I want to restructure those groups of sequences where the maximum > 4. The ascending order should remain the same but the maximum number must be 4. To do that I need to duplicate one or more middle digits.我想重组最大值 > 4 的那些序列组。升序应该保持不变,但最大数字必须为 4。为此,我需要复制一个或多个中间数字。 So I want the column to look like this:所以我希望该列看起来像这样:

column
1
2
2
2
3
4
0
1
2
3
4
1
2
2
3
4
0
0

Zeros should be left as they are.零应该保持原样。

I tried to, first, make the grouping variable:首先,我尝试使分组变量:

k = 0
l = 1
i = 0

for k in range(1, len(df)):
    if df.loc[k, 'column'] != 0:
        if  df.loc.loc[k, 'column'] > df.loc.loc[k-1, 'column']:
            df.loc.loc[k, 'position'] = l
        else:
            l = l + 1
            df.loc.loc[k, 'position'] = l
    else:
         df.loc.loc[k, 'position'] = 0
         l = l + 1

l=pd.DataFrame(df.loc.groupby('position')['columns'].max()).reset_index()

And then I tried to come up with something like this but this does not work with different maximum values (not only 4):然后我试图想出这样的东西,但这不适用于不同的最大值(不仅仅是4):

z = 1
r = 0

for z in range (1, len(l)-1):
  if l.loc[z,'column'] > 4:
     for r in range(0, l.loc[z,'column'] - 3):
                df.loc[df['column']==2+r, 'column'] = 2

    df['column'] = np.where(df['column'] > 2, df['column'] - r, df['column'])

Please help!请帮忙!

Use groupby to group by each group of monotonic increases, and then do some math do normalize back to the 1-4 range:使用groupby对每组单调增加进行分组,然后做一些数学归一化回到 1-4 范围:

MAX_NUMBER = 4
>>> df['column'].groupby((df['column'].diff() < 0).cumsum())\
               .apply(lambda s: s//(max(s)/MAX_NUMBER))\
               .fillna(0)

What I did here was just to absolute divide all numbers by max(s)/4 and the final result was quite similar to yours.我在这里所做的只是将所有数字绝对除以max(s)/4 ,最终结果与您的非常相似。 But feel free to use any custom function you want (eg you can set 0, 1 manually to the first positions, and 3, 4 to the last, and just fill 2 in between; etc).但是您可以随意使用您想要的任何自定义函数(例如,您可以手动将 0、1 设置为第一个位置,将 3、4 设置为最后一个位置,然后在中间填充2等)。

   column
0     0.0
1     1.0
2     2.0
3     2.0
4     3.0
5     4.0
6     0.0
7     1.0
8     2.0
9     3.0
10    4.0
11    0.0
12    1.0
13    2.0
14    3.0
15    4.0
16    0.0
17    0.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM