Is there a loop or function that I can use in Python to simplify down this code, so that I can go through an entire list and return the result of each iteration? I need to apply the value of the row index to iloc and as a function parameter.
I've tried while loops, but I get <function __main__.()>
in return when I put it in a function.
IndexList = [0,1,2,3,4,5,6,...,99]
IndexPosition = 0
row_index = IndexList.index[IndexPosition]
Result = dfColumn1.iloc[row_index] / dfFunction(row_index)
Result
#Output
IndexPosition = 1
row_index = IndexList.index[IndexPosition]
Result = dfColumn1.iloc[row_index] / dfFunction(row_index)
Result
#Output
IndexPosition = 2
row_index = IndexList.index[IndexPosition]
Result = dfColumn1.iloc[row_index] / dfFunction(row_index)
Result
#Output
etc
Ideally, I'd like it so the output is:
#Output of function from Index Position 1
#Output of function from Index Position 2
#Output of function from Index Position 3
#Output of function from Index Position 4
CodePudding user response:
I think you can use a for(each) loop with index using the built-in function enumerate():
for value, index in enumerate(IndexList):
print(value, index)
CodePudding user response:
You might want to take a few steps back from the columns and indexes you extracted. Pandas dataframes offer a lot of direct ways to iterate over the columns or cells themselves.
import pandas as pd
df = pd.DataFrame({'x': {0: 1, 1: 200, 2: 4, 3: 5, 4: 6},
'y': {0: 4, 1: 5, 2: 10, 3: 24, 4: 4},
'z': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}
})
results = []
for idx, x in enumerate(df.iloc[:, 1]):
results.append(df.iloc[idx] / dfFunction(x))
for res in results:
print(res)