How to access an attribute or method from a variable?

Asked

Viewed 34 times

-1

I’m getting this mistake:

Erro: " 'Series' object has no attribute 'medida' "

Is there any way to put a variable in place of the method and Dataframe recognizes the attribute? Below is the code as I thought it would work.

   def desc():
        lista_colunas = ['Pclass', 'Age', 'Parch', 'Fare']
        lista_medidas = ['mean','max','min','std','var']
        for medida in lista_medidas:
            for feat in lista_colunas:
                df_join[feat + '_' + medida] = df_join[feat].medida()
        df_join.head()
    desc()
  • In the pandas.DataFrame No! You’d have to do a style gambiarra Monkey patch how to overwrite in Runtime the class pandas.Series to include the method pandas.Series.medida().

2 answers

0

You can take a method / attribute any of an object through a string with the function built-in getattr:

import numpy as np

a = np.array([1, 2, 3])
# a linha abaixo equivale a escrever "soma = a.sum()"
soma = getattr(a, 'sum')()

print(soma)  # output = 6

Without sample data, I can’t test if your code logic is working. But by focusing on your question, you can do the operation with:

df_join[feat + '_' + medida] = getattr(df_join[feat], medida)()
  • I don’t think so. I understood that the AP wants to add a new method to the class pandas.Series.

  • "put a variable in place of the method and the Dataframe recognize the attribute" seems to me rather with the description of a beginner who wants to use the value of the variable medida = "mean" to access the method df.mean dynamically, but realized that neither df.medida nor df."mean" work. Anyway it would be good if the OP comes back to try to clarify your doubt.

0

You can use the eval to do what you want.

def desc():
    lista_colunas = ['Pclass', 'Age', 'Parch', 'Fare']
    lista_medidas = ['mean','max','min','std','var']
    for medida in lista_medidas:
        for feat in lista_colunas:
            func = f"df_join['{feat}'].{medida}()"
            df_join[feat + '_' + medida] = eval(func)
    print(df_join.head())

desc()

Note Beware of using the eval. In certain situations where the program has a security breach, the use of this can be dangerous. Imagine that in this small script it is possible to insert value to func. If a person with a bad intensity enters select * from table or just 1/0, or something else; the script could throw an exception, delete files, elevate CPU usage by 100% or other problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.