Reputation: 61
I am doing a loop where it involves two variables. I already have solved the first one but the second one is quite a challenge.
What I have done so far is shown below.
columns = ('node2', 'node3', 'node4', 'node5', 'node6', 'node7', 'node8', 'node9')
node = pd.concat([L1_20['node1'], L2_20['node1'], L3_20['node1'], L4_20['node1']],axis=1)
for i in columns:
node = pd.concat([node, L1_20[f'{i}'], L2_20[f'{i}'], L3_20[f'{i}'], L4_20[f'{i}']],axis=1)
node
As you can see, I was able to work with cahnging the column names from "node1" to "node9"
However, I also wanted to change my varialbes in the 4th line of my code. The variables are L1_20, L2_20, L3_20, and L4_20 respectively.
So I tried to incorporate this code.
acceleration = (20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90)
i = 20
for i in range(len(acceleration)):
print('L1_'+str(acceleration[i]))
Output:
So my code now looks like this:
columns = ('node2', 'node3', 'node4', 'node5', 'node6', 'node7', 'node8', 'node9')
acceleration = (20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90)
x = 20
node = pd.concat([L1_25['node1'], L2_25['node1'], L3_25['node1'], L4_25['node1']],axis=1)
for i in columns:
for x in range(len(acceleration)):
node = pd.concat([node, 'L1_'+str(acceleration[x])[f'{i}'], 'L2_'+str(acceleration[x])[f'{i}'], 'L3_'+str(acceleration[x])[f'{i}'], 'L4_'+str(acceleration[x])[f'{i}']],axis=1)
node
which I got an error saying: "string indices must be integers"
What did I do wrong?
Upvotes: 0
Views: 408
Reputation: 1434
You are building a string and then indexing it as if it was the variable of the same name, it has no relation to the variable it is just a new string. In order to build the name of a variable and use it you can map the string to the variable using a dictionary and index the dictionary to use the variable.
I believe you are trying to concatenate all of the combinations into one Dataframe, if this is the case you can select all columns for each seperate dataframe and append them to node
together:
mapping = {
'L1_25': L1_25,
'L2_25': L2_25,
'L3_25': L3_25,
'L4_25': L4_25,
... # build for all combinations
}
columns = ['node2', 'node3', 'node4', 'node5', 'node6', 'node7', 'node8', 'node9']
acceleration = [20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90]
node = pd.DataFrame()
for i in range(1, 5):
for acc in acceleration:
node = pd.concat([mapping[f'L{i}_{acc}'][columns], node], axis=1)
Upvotes: 1