根据条件枚举每个dtaaframe组的行

时间:2017-09-15 20:17:45

标签: python pandas dataframe group-by

我想使用某些条件重新枚举给定public static string ConvertHex(String hexString) { try { //DECLARE A VARIABLE TO RETURN string ascii = string.Empty; //SPLIT THE HEX STRING BASED ON SPACE (ONE SPACE BETWEEN TWO NUMBERS) string[] hexSplit = hexString.Split(' '); //LOOP THROUGH THE EACH HEX SPLIT foreach (String hex in hexSplit) { // CONVERT THE NUMBER TO BASE 16 int value = Convert.ToInt32(hex, 16); // GET THE RESPECTIVE CHARACTER string stringValue = Char.ConvertFromUtf32(value); char charValue = (char)value; //APPEND THE STRING ascii += charValue; } //RETURN THE STRING return ascii; } catch (Exception ex) { Console.WriteLine(ex.Message); } return string.Empty; } 中的行。我的问题是这个question的扩展。

df的示例:

df

ind seq status 0 1 2 up 1 1 3 mid 2 1 5 down 3 2 1 up 4 2 2 mid 5 2 3 down 6 3 1 up 7 3 2 mid 8 3 3 oth 包含代表df列。 ind列可能包含一些错误数据。我希望根据某些条件添加另一列seq来更正seq_corr枚举:

  • seq列中的组中的第一个值等于status
  • up列中的组中的最后一个值等于statusdown
  • 在所有其他情况下,从oth列复制号码。

我知道这样做的合理方法但我有一些麻烦如何将其转换为seq。特别是在适当切片和访问每组的第一个和最后一个元素时。

下面你可以找到我不能正常工作的代码:

Python

预期结果:

 def new_id(x):
    if (x.loc['status',0] == 'up') and ((x.loc['status',-1]=='down') or (x['status',-1]=='oth')):
        x['ind_corr'] = np.arange(1, len(x) + 1)
    else:
        x['seq_corr']= x['seq']
    return x

 df.groupby('ind', as_index=False).apply(new_id)

希望有人能够指出任何解决方案。

3 个答案:

答案 0 :(得分:1)

让我们尝试df.groupby后跟applyconcatenat离子。

vals = df.groupby('ind').apply(
       lambda g: np.where(g['status'].iloc[0] == 'up' 
                       or g['status'].iloc[-1] in {'down', 'oth'},
      np.arange(1, len(g) + 1), g['seq'])
).values

df['seq_corr'] = np.concatenate(vals)
df
   ind  seq status  seq_corr
0    1    2     up         1
1    1    3    mid         2
2    1    5   down         3
3    2    1     up         1
4    2    2    mid         2
5    2    3   down         3
6    3    1     up         1
7    3    2    mid         2
8    3    3    oth         3

答案 1 :(得分:1)

使用groupby cumcount的另一种方法。要选择第一行和最后一行,我们可以使用head和tail方法并将它们的索引联合起来。我认为这可能有助于你的第二个问题

df['seq_corr'] = df.groupby('ind').cumcount()+1
idx = df.groupby('ind').head(1).index.union(df.groupby('ind').tail(1).index)

df.loc[idx,'seq_corr'] = np.where(~df.loc[idx,'status'].isin(['up','down','oth']),
                                    df.loc[idx,'seq'],df.loc[idx,'seq_corr'])

示例输出:

   ind  seq status  seq_corr
0    1    2     up         1
1    1    3    mid         2
2    1    5  dance         5
3    2    1     up         1
4    2    2    mid         2
5    2    3   down         3
6    3    1     up         1
7    3    2    mid         2
8    3    3    oth         3

答案 2 :(得分:0)

感谢@cᴏʟᴅsᴘᴇᴇᴅ我已经更正了我的代码。看一下第一次测试,一切都还可以。

 def new_id(x):
    if (x['status'].iloc[0] == 'up') and ((x['status'].iloc[-1]=='down') or (x['status'].iloc[-1]=='oth')):
    x['seq_corr'] = np.arange(1, len(x) + 1)
    else:
    x['seq_corr']= x['seq']
    return x