Python Forum
Use pandas to obtain cartesian product between a dataframe of int and equations? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Use pandas to obtain cartesian product between a dataframe of int and equations? (/thread-39134.html)



Use pandas to obtain cartesian product between a dataframe of int and equations? - haihal - Jan-06-2023

I've attached an image further detailing what I'm trying to achieve.

The following is what I came up with; but I'm confident it can be done much simpler with built pandas modules. I'm hoping I won't have to resort to nested 4 loops.

The following is the code I used in the python interpreter:

nestDict =  {   'A': {'Entity 1': 2, 'Entity 2': 1, 'Entity 3': 2},
                'B': {'Entity 1': 4, 'Entity 2': 6, 'Entity 3': 3},
                'C': {'Entity 1': 5, 'Entity 2': 8, 'Entity 3': 4}
            }
frame1 = pd.DataFrame(nestDict)

dict1 = {   'Squared' : 'x**2', 
            'Sqrt' : 'round(math.sqrt(x), 2)', 
            'isPrime' : 'is_Prime_Function(x)'
        }
series1 = pd.Series(dict1)

def is_Prime_Function(n):
    if n == 1:
        return 0        
    for i in range(2,n):
        if (n%i) == 0:
            return 0
    return 1

frame1_sqrd = frame1.applymap(lambda x:eval(series1['Squared']))    
frame1_sqrt = frame1.applymap(lambda x:eval(series1['Sqrt']))
frame1_isPrime = frame1.applymap(lambda x:eval(series1['isPrime']))

# Use nested for loop to retrieve each row from the evaluated frames make results 'readable' from 1 single 'cartesian-like' dataframe.
This is the best or closes I've gotten to getting what I'm looking for.

def triple_Evaluation(x):
    return pd.Series([x**2, round(math.sqrt(x), 2), is_Prime_Function(x)], index=['Squared','Sqrt','Is Prime'])
    
frame1.iloc[[0]].append(frame1.iloc[0].apply(triple_Evaluation).T)