I have a loop where I constantly got an error message.
print(((df1['col1_df'] == 0) & (df1['col2_df'] == True)).sum()) print(((df1['col1_df'] == 0) & (df1['col3_df'] == True)).sum()) print(((df1['col1_df'] == 0) & (df1['col4_df'] == True)).sum()) print(((df1['col1_df'] == 0) & (df1['col5_df'] == True)).sum()) print(((df2['col1_df'] == 0) & (df2['col2_df'] == True)).sum()) print(((df2['col1_df'] == 0) & (df2['col3_df'] == True)).sum()) print(((df2['col1_df'] == 0) & (df2['col4_df'] == True)).sum()) print(((df2['col1_df'] == 0) & (df2['col5_df'] == True)).sum())
I want to loop them through a function.
So far I have:
for i in range (2,5): col = "col{}_df".format(i) print(((df['col'] == 0) & (df['col'] == 2)).sum())
How can I number the df and let the df go through 1, 2, 3, 4 (like df1, df2 df3)
Advertisement
Answer
col
is a variable. 'col'
is a string. Having df['col']
doesn’t refer to the variable col
.
Your string format is done wrong: col = "col{}_df".format(i)
Also, range(2,5)
will give you [2,5)
not [2,5]
. It is not inclusive.