'Storing data in different variable during a FOR loop

I have this code:

import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

sens_fac = [0.8, 1, 1.2]
A = 13;
B = 5;
C = 7/2;
D = 3*1.2;
par = [A,B,C,D]
data = pd.DataFrame(index=range(len(sens_fac)),columns=range(len(par)))
term1 = pd.DataFrame(index=range(len(sens_fac)),columns=range(len(par)))
term2 = pd.DataFrame(index=range(len(sens_fac)),columns=range(len(par)))
term3 = pd.DataFrame(index=range(len(sens_fac)),columns=range(len(par)))
term4 = pd.DataFrame(index=range(len(sens_fac)),columns=range(len(par)))
sol = []

for i in range(len(par)):
    factors = [1, 1, 1, 1]
    for j in range(len(sens_fac)):
        factors[i] = sens_fac[j]
        print(factors)
        x=25
        t1 = np.log(x)**math.sin(x/(A*factors[0]))
        t2 = (B*factors[1])*math.sqrt(x)
        t3 = (factors[2]*C)**math.exp(1/x)
        t4 = x/(factors[3]*D)*2
        res = t1 + t2 + t3 + t4
        term1[i][j] = t1
        term2[i][j] = t2
        term3[i][j] = t3
        term4[i][j] = t4
        data[i][j] = res

print(term1)
print(term2)
print(term3)
print(term4)

The dataframes term1, term2, ... , termX only are different in a specific step of the FOR loop. For instance, term1 have different values only when i=0, but are the same for i=1, i=2 or i=3. On the other hand, term2 have different values when i=1 but keep the same values for the rest of the iterations. Actually, you can see this in the DataFrame:

term1 =

          0         1         2         3
0  2.195296  2.995886  2.995886  2.995886
1  2.995886  2.995886  2.995886  2.995886
2  3.216978  2.995886  2.995886  2.995886

term2 =

      0     1     2     3
0  25.0  20.0  25.0  25.0
1  25.0  25.0  25.0  25.0
2  25.0  30.0  25.0  25.0

I would like to obtain something like this:

term1 =

          0         
0  2.195296 
1  2.995886  
2  3.216978  

or term2 =

      0     
0  20.0
1  25.0
2  30.0

How can I do it?



Solution 1:[1]

You can drop the columns with only one unique element (keep columns with more than one unique element):

term1.loc[:, term1.nunique().gt(1)].squeeze()

output:

0    2.195296
1    2.995886
2    3.216978
Name: 0, dtype: float64

NB. you can use squeeze to convert the unique matching column to Series and thus be able to use them in operations without worrying about index alignment

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway