I have a dataframe that looks as follows:
JavaScript
x
5
1
alpha_0 alpha_1 alpha_2 alpha_3
2
1 2 1 4
3
2 0 3 8
4
0 0 0 9
5
Beta is calculated as ((sum of each row)^2)/10. I want to keep dropping columns until Beta is less than or equal to 1 for all rows.
So far I have
JavaScript
1
8
1
n_alphas=4
2
for alpha in range(0,n_alphas):
3
df.drop(list(values.filter(regex = 'alpha '+str(alpha))), axis = 1,
4
inplace = True)
5
6
Beta=(df.sum(axis=1)^2)/10
7
print(Beta)
8
How can I stop the loop when all values of beta are below or equal to 1?
Advertisement
Answer
First of all, if you want to calculate the power of a number, do not use ^
operator. It is an XOR Boolean operator. Instead, use **
operator.
This code should work. However, this will also delete last remaining column from the dataframe, if the condition of Beta is not met.
JavaScript
1
5
1
for column in df.columns:
2
Beta = (df.sum(axis=1) ** 2) / 10
3
if Beta.min() > 1.0:
4
df.drop(columns=[column], inplace=True)
5
If you do not want the last remaining column to be deleted even if the Beta condition is not met, use this code
JavaScript
1
6
1
n_alphas = 4
2
for alpha in range(0, n_alphas):
3
Beta = (df.sum(axis=1) ** 2) / 10
4
if Beta.min() > 1.0:
5
df.drop(columns=[f"alpha_{alpha}"], inplace=True)
6