How To Select A Column Name And Use It As Input For A Variable Name In Python?
ORIGINAL QUESTION: I'm writing a while loop to loop over certain columns. In this while loop I want to create a variable of which the name partly consists of the column name it is
Solution 1:
You shouldn't create variables on-the-fly as it could lead to many issues, instead, use dictionary:
largest = {}
x = 2length = len(grouped_class.columns)
whilex < length:
x = x + 1
column = grouped_class.columns[x]
largest[column + '_largest'] = x + 5
...
Solution 2:
Right way: The right (Pythonic) way is to use dictionaries.
columns = {}
columns[some_string] = some_value
Unadvised dirty way, but answers your question: Storing a string as a variable name in your global namespace can be done simply by (example):
some_value = 100
some_string = 'var_name'
globals()[some_string] = some_value
The output is then
>>>var_name
100
On the other hand, if you want to add a variablename locally, you can use locals()
instead of globals()
.
I trust you can take over from here!
Solution 3:
You do not want to do that. Of course dirty tricks can allow it, but the Pythonic way is to use a dictionary:
largest = {}
x = 2
length = len(grouped_class.columns)
while x < length:
x = x + 1
largest[grouped_class.columns[x]] = x + 5
Solution 4:
Looks like you are using a pandas dataFrame. You can use:
dict = {}
my_dict[grouped_class.columns[x]+'_largest'] = x+5
Post a Comment for "How To Select A Column Name And Use It As Input For A Variable Name In Python?"