Skip to content Skip to sidebar Skip to footer

Why Is It Not Possible To Access Other Variables From Inside The Apply Function In Python?

Why would the following code not affect the Output DataFrame? (This example is not interesting in itself - it is a convoluted way of 'copying' a DataFrame.) def getRow(row): O

Solution 1:

What happens

DataFrame.append() returns a new dataframe. It does not modify Output but rather creates a new one every time.

   DataFrame.append(self, other, ignore_index=False, verify_integrity=False)

Append rows of other to the end of this frame, returning a new object. Columns not in this frame are added as new columns.

Here:

Output.append(row)

you create a new dataframe but throw it away immediately.

You have access - But you shouldn't use it in this way

While this works, I strongly recommend against using global:

df = DataFrame([1, 2, 3])
df2 = DataFrame()

defget_row(row):
    global df2
    df2 = df2.append(row)

df.apply(get_row)
print(df2)

Output:

   0  1  2
0  1  2  3

Take it as demonstration what happens. Don't use it in your code.

Post a Comment for "Why Is It Not Possible To Access Other Variables From Inside The Apply Function In Python?"