Reputation: 57
I have 3 dataframes that I'm working with that has the same column names and that I'm working on merging them. The first column is for the dataframes I want the same. The rest of the columns are years, and I wanted to add a letter to each of years to distinguish between the dataframes. I was able to do this manually without any issues. But when I tried defining a function, I get the following error
NameError: name 'x' is not defined.
This is my initial attempt without defining a function. dfyears is the dataframe I'm trying to change the columns names with. The first column 'City_State', I want to keep the same, and the rest I want to add a letter behind depending on the dataframe.
dfyearlist = (dfyears.columns[1:].values.tolist())
dfcols = [(dfyears.columns[0])]
for i in dfyearlist:
dfcols.append(i + 'r')
dfyears.columns = dfcols
Here's the first 3 lines of my output:
City_State 2010r 2011r 2012r 2013r \
0 New York, NY 1771.666667 1753.384615 1803.615385 1955.384615
1 Los Angeles, CA 2190.333333 2185.076923 2185.000000 2242.692308
2 Houston, TX 1198.666667 1195.538462 1197.846154 1252.692308
2014r 2015r 2016r 2017r 2018r
0 2124.000000 2271.230769 2331.846154 2337.384615 2295.846154
1 2331.384615 2522.692308 2687.000000 2798.307692 2883.153846
2 1322.076923 1411.461538 1439.461538 1423.615385 1432.923077
But when I tried defining a function:
def changecolumnnames(s, x):
templist = [s.columns[1:].values.tolist()]
returnlist = [(s.columns[0])]
for i in templist:
returnlist.append(i + str(x))
s.columns = returnlist
zillrentyears = changecolumnnames(zillrentyears, r)
I get:
NameError: name 'r' is not defined.
Not sure what I'm doing wrong here?
Upvotes: 0
Views: 2463
Reputation: 10873
r
is a string and you're trying to pass it as a variable.
You need to change your function to hangecolumnnames(zillrentyears, "r")
and then inside the function you can call returnlist.append(i + x)
without using str
.
Upvotes: 1
Reputation: 4255
x is not defined outside of changecolumnnames
You provide r as an input to changecolumnnames. r is your x outside of changecolumnnames
Upvotes: 0