public static bool IsBalanced(string input)
{
Dictionary<char, char> bracketPairs = new Dictionary<char, char>() {
{ '(', ')' },
{ '{', '}' },
{ '[', ']' },
{ '<', '>' }
};
Stack<char> brackets = new Stack<char>();
try
{
// Iterate through each character in the input string
foreach (char c in input)
{
// check if the character is one of the 'opening' brackets
if (bracketPairs.Keys.Contains(c))
{
// if yes, push to stack
brackets.Push(c);
}
else
// check if the character is one of the 'closing' brackets
if (bracketPairs.Values.Contains(c))
{
// check if the closing bracket matches the 'latest' 'opening' bracket
if (c == bracketPairs[brackets.First()])
{
brackets.Pop();
}
else
// if not, its an unbalanced string
return false;
}
else
// continue looking
continue;
}
}
catch
{
// an exception will be caught in case a closing bracket is found,
// before any opening bracket.
// that implies, the string is not balanced. Return false
return false;
}
// Ensure all brackets are closed
return brackets.Count() == 0 ? true : false;
}
Вы можете использовать pd.concat
с groupby
и использовать пользовательскую функцию для заполнения логики:
# convert to numeric
df['Number'] = pd.to_numeric(df['Number'])
# assign values by index
def filler(x):
idx = np.where(x['Number'].notnull())[0]
x.iloc[:idx[0], -2:] = ['1. Too Low', 1]
x.iloc[idx[-1]+1:, -2:] = ['3. Too High', 3]
return x
# concatenate transformed dataframe slices
res = pd.concat(df_slice.pipe(filler) for _, df_slice in df.groupby('Department'))
Результат:
print(res)
Department Range Rating Number
0 Admin 0 (None) 1. Too Low 1.0
1 Admin 01 to 3 1. Too Low 1.0
2 Admin 01 to 3 1. Too Low 1.0
3 Admin 01 to 3 1. Too Low 1.0
4 Admin 04 to 6 2. On Target 2.0
5 Admin 04 to 6 2. On Target 2.0
6 Admin 04 to 6 2. On Target 2.0
7 Admin 07 to 10 3. Too High 3.0
8 Admin 07 to 10 3. Too High 3.0
9 Admin 07 to 10 3. Too High 3.0
10 Admin 07 to 10 3. Too High 3.0
11 Distribution 0 (None) 1. Too Low 1.0
12 Distribution 01 to 3 1. Too Low 1.0
13 Distribution 01 to 3 1. Too Low 1.0
14 Distribution 01 to 3 1. Too Low 1.0
15 Distribution 04 to 6 2. On Target 2.0
16 Distribution 04 to 6 2. On Target 2.0
17 Distribution 04 to 6 2. On Target 2.0
18 Distribution 07 to 10 3. Too High 3.0
19 Distribution 07 to 10 3. Too High 3.0
20 Distribution 07 to 10 3. Too High 3.0
21 Distribution 07 to 10 3. Too High 3.0