RobH
RobH

Reputation: 1261

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 looping over.

x=2
length=len(grouped_class.columns)
while x<length:
    x=x+1
    (grouped_class.columns[x])_largest = x+5
    ...

This is my current code (=x+5 is not actual code, but as example), but it returns a syntax error. If I run grouped_class.columns[x] in the shell it returns the name of that column, for example : "ColumnA". I want to use this "ColumnA" as first part of a variable name.

So in the variable list it would return: ColumnA_largest

In this way I can store the result for each column in a seperate variable.

How can I do this?

EDIT: QUESTION GENERALIZED

How can I use a string obtained by df.column[x] as input for a variable name?

Example df:

ColumnA    ColumnB    ColumnC
5          6          4
6          10         2

If I run df.columns[1] it returns "ColumnB"

I want to use this "ColumnB" as part of the name when assigning a variable.

Imagine I want to create the variable COLNAME_sum = x + 5 I would like to change the COLNAME to the string I obtained from df.columns[1] (="ColumnB")

Expected output: A variable named ColumnB_sum.

How can I do this?

Upvotes: 2

Views: 5239

Answers (4)

zipa
zipa

Reputation: 27879

You shouldn't create variables on-the-fly as it could lead to many issues, instead, use dictionary:

largest = {}
x = 2
length = len(grouped_class.columns)
while x < length:
    x = x + 1
    column = grouped_class.columns[x]
    largest[column + '_largest'] = x + 5
    ...

Upvotes: 1

amalik2205
amalik2205

Reputation: 4172

Looks like you are using a pandas dataFrame. You can use:

dict = {}
my_dict[grouped_class.columns[x]+'_largest'] = x+5

Upvotes: 1

Serge Ballesta
Serge Ballesta

Reputation: 149095

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

Upvotes: 1

WiseDev
WiseDev

Reputation: 535

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!

Upvotes: 1

Related Questions