0

I want to call a variable that was created as a string. For example,

import pandas as pd
a_1 = pd.series([1, 2, 3])
a_2 = pd.series([2, 3, 4])
a_3 = pd.series([3, 4, 5])

Now I want to use a for loop to call all these variables. Something like:

for i in range(1,4):
  print(a_{i})

I have tried using placeholders but they do not work for series.

Kiran
  • 45
  • 5
  • 3
    Don't try to dynamically use variables like this. **Use a container** like a list, or a dict, (or in this case, a dataframe?). It is very important to understand, *variables are not strings*. Variables are a part of *source code*. – juanpa.arrivillaga Apr 20 '21 at 18:48
  • 1
    Also, a terminology note, the word "call" has a specific meaning, and it doesn't mean what you are using it to mean. You are trying to "reference" or "access" a variable. – juanpa.arrivillaga Apr 20 '21 at 18:49

2 Answers2

1

The right way to do that is to add them to a list.

a = []
a.append( pd.series([1,2,3]) )
a.append( pd.series([2.3.4]) )
a.append( pd.series([3.4.5]) )
...
for row in a:
    print( row)

The reason why your code is wrong is rather subtle. Remember that a Python variable doesn't know it's own name. The variable's name is just a convenience for you and the interpreter. Objects are all anonymous. I'm sure someone will chime in to point out that it is possible to do what you want, by looking up the name in the globals() dictionary, but that's absolutely the wrong way to solve this problem. If you need a collection, then use a collection.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

you can use dict -

import pandas as pd
my_dict = {'a_1': pd.Series([1, 2, 3])}
my_dict['a_2'] = pd.Series([2, 3, 4])
my_dict['a_3'] = pd.Series([3, 4, 5])
for item, value in my_dict.items():
    print(value)
Nk03
  • 14,699
  • 2
  • 8
  • 22