Search code examples
pythonpandasdataframerangestring-concatenation

Concatenating a string with a range


x= ("bonus")
i=[str(i) for i in range(80,121)]
for s in i:
    z=x+s

I am trying to get an outcome of

bonus80
bonus81
bonus82
...
..
bonus120

So I could use the outcome for below code

bonus_80=df["Bonus Payout 80%"].values
bonus_81=df["Bonus Payout 81%"].values
# ...
bonus_119=df["Bonus Payout 119%"].values
bonus_120=df["Bonus Payout 120%"].values

But still could not find a way to do it, I tried many variations to no end.


Solution

  • I believe what you want is to dynamically create variables. As @JarroVGIT mentionned, using a dictionary is better. But otherwise you can access the globals() dictionary to access variable names :

    for i in range(80, 121):
        globals()[f"bonus_{i}"] = df[f"Bonus Payout {i}%"].values
    

    Then you have your 20 independant variables and you can access them like any other.

    bonus_110 = 110
    print(bonus_84)