I have a large number of corresponding columns: colA1, colA2... colA60 and colB1, colB2... colB60. Based on the values of colA1 and colB1, I would like to create colC1. How can I create a function which iterates through i in range 1 to 3 for colAi, colBi and colCi? In reality the range is much larger.
I've managed to create a list of column names:
range_list= list(range(1,4))
for i in range(0, len(range_list)):
range_list[i] = str(range_list[i])
A_list= ['colA' + s for s in range_list]
B_list= ['colB' + s for s in range_list]
C_list= ['colC' + s for s in range_list]
Some sample data:
my_dict = {'colA1':[2,6,8,28,5],
'colA2': [38,6,14,63,3],
'colA3':[90,40,80,98,3],
'colB1':[1,46,23,4,42],
'colB2': [24,3,9,10,24],
'colB3':[35,12,19,3,23]}
df = pd.DataFrame(my_dict)
How can I iterate through these corresponding columns in a function? Here is my attempt which doesn't work at all.
def test_fx(x):
for a in range(len(A_list)) and b in range(len(B_list)):
c == df[a]
if df[b] >= 10:
c = df[a]*2
elif [b] >= 20:
c = df[a]*3
elif [b] >= 30:
c = df[a]*4
return c
for c in range(len(C_list)):
df[c] = 'empty'
df[c].apply(test_fx)
The expected output is three columns added to df:
colC1: 2,24,24,28,20
colC2: 114,6,14,126,9
colC3: 360,80,160,98,9