Python - Problem with df.apply(Function)

Asked

Viewed 34 times

0

beauty?

Can I get a little help? Just call.

I have a dataframe with some string information and wanted to change them to text.

To simplify, imagine that the table contains information of the person’s gender, for example, male or female. My program would classify as 0 or 1.

Until he can do it well. But the problem is when I have a lot of information inside the table, the program is running all day. when I run out of patience and cancel, sometimes he converted the units and sometimes not.

my python code ta so oh:

```python
y='Indice da Tabela'

def toText(x):
        return(list(train[y].value_counts().index).index(x))

train[y]=train[y].apply(toText)
```

1 answer

0

I figured out the problem. Probably the function of staying indexed all the time in the variable was giving problems. I played the part of (train[i].value_counts().index) out of the loop and improved the code.

```python
def transf(df):
    nome=list(df)
    for i in (nome):
        def toText(x):
            return(y_.index(x))
        y_ = list(train[i].value_counts().index)
        if df[i].dtype == 'O':
            train[i]=train[i].apply(toText)

Stayed until the code became attractive at the end.

Browser other questions tagged

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