Reputation: 83
I'm trying to reindex dataframes within a function but it's not working. It works outside of the function so I'm totally lost. Here's what I'm doing:
Reindexing df2 based on index from df1
Outside of function:
df2 = df2.reindex(df1.index)
This result is what I want ,and works. However, within this function:
def reindex_df(a,b):
a = a.reindex(b.index)
where a = df2
and b = df1
.
What's going on here? I've researched and thought something to do with local vs. global variables, but tweaked code (to this) and still not working. What am I missing????
Upvotes: 0
Views: 121
Reputation: 30991
Compare 2 following examples:
A function substituting a new value under a parameter:
def f1(a):
a = a + 1
a = 10
print(f'Before: {a}')
f1(a)
print(f'After: {a}')
The result is:
Before: 10
After: 10
so that the substitution in f1 is not visible outside this function.
A function returning the new value:
def f2(a):
return a + 1
a = 10
print(f'Before: {a}')
a = f2(a)
print(f'After: {a}')
This time the result is:
Before: 10
After: 11
So change your function the same way. It should return the new (reindexed) DataFrame and when you call it, substitute the result under the same variable.
Upvotes: 1