'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 1:[1]
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)
Solution 2:[2]
Try using a dictionary for dynamic key/value pairs.
result = {}
for i in range (80,121):
result[f"Bonus_{i}"] = df[f"Bonus Payout {i}%"]
Solution 3:[3]
x= ("bonus")
i=[str(i) for i in range(80,121)]
for s in i:
z=x+s
I would tell you "Nice try", but have you noticed that you're not printing anything?
I would do this:
l = [f"Bonus Payout {i}%" for i in range(80, 120)]
and then, if you want to access that df:
n = [df[key] for key in l]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | JarroVGIT |
| Solution 3 | FLAK-ZOSO |
