illuminato
illuminato

Reputation: 1257

How to write an iterative function

I have the next for-loop:

dfs_fixed = []
for i in range(len(dfs)):
    dfs_fixed.append(dfs[i][dfs[i]['paragraph'].notnull()].reset_index(drop=True))

where dfs is a list of dataframes.

I need to do a function from it. Here is my solution:

def append_to_list(data_list, function):
    data = []
    for i in range(len(customer_data_set)):
        data.append(function)
    return data

But it doesn't work. When I run:

dfs_fixed = append_to_list(dfs, dfs[i][dfs[i]['paragraph'].notnull()].reset_index(drop=True))

I am getting:

NameError: name 'i' is not defined

Is there any way to create an appropriate append_to_list function?

Upvotes: 0

Views: 42

Answers (2)

eje211
eje211

Reputation: 2429

Two things.

First, when you run

dfs_fixed = append_to_list(dfs, dfs[i][dfs[i]['paragraph'].notnull()].reset_index(drop=True))

You're already using a variable i. If it has not yet been defined, you cannot yet use it.

Also, in your example, you're using C-style for loops as opposed to Python-style for loops.

You don't need to do:

for i in range(len(l)):
     print(l[i])

Just do:

for i in l:
     print(i)

If you need both value and index do:

for i, v in enumerate(l):
     print('value: %s; index: %s' % (v, i))

Upvotes: 0

chepner
chepner

Reputation: 531165

i is only defined inside the function. You need to pass dfs alone as the argument, along with a function that takes an element of data_list as its argument

dfs_fixed = append_to_list(dfs, lambda d: d[d['paragraph'].notnull()].reset_index(drop=True))

and define the function something like

def append_to_list(data_list, f):
    data = []
    for d in data_list:
        data.append(f(d))
    return data

Upvotes: 1

Related Questions