Why can't I edit a global variable using map?

Viewed 25

I am currently in the process of manipulating data from a pd.DataFrame, to several numpy matrices. I am doing this by first creating the matrix as a global variable, and then iterating through the rows, and columns filling the matrix observation by observation.

I am using map() and a function I have defined myself within a for-loop to achieve this.

However, the matrix always results to be empty (same state as initialisation). This is not because of a local vs global scope problem because I have included the global keyword and nonlocal keyword correctly.

I think it has something to do with the map() because my function works fine in a for-loop. The problem persists when I use itertools.accumulate.

My question is: WHY can't I change the global variable using map, and HOW else can I do this, preferably with another function like map.

The code below is meant to represent the sort of thing I am trying to do. I am using such a complicated approach because my actual DataFrame has a very complicated structure. I've purposefully simplified the Data frame in the code below.

d = {0: [0,0,0,0], 1: [1,2,3,4], 2: [2,4,6,8], 3:[3,6,9,12]}
myData = pd.DataFrame(data=d)

# global matrix
M = np.zeros((4,4),int)

def foo(r,c,value):
    global M
    M[r,c] = value

### DOESN'T work
for r, r_data in myData.iterrows():
    cols = r.index()
    map(lambda c, r=r, value=myData[r,c]: foo(r, c, value),cols) 

### WORKS
for r, r_data in myData.iterrows():
    cols = r.index()

    for c in colds:
        foo(r, c, myData[r,c]) 

This is my first-ever question on Stackoverflow; I hope I was clear enough!

0 Answers
Related