Search code examples
pythondataframenaivebayes

How to do two for loops in a single python loop?


I don't mean to shortening this:

for x in data1:
    for y in data2:
        *lines*

but to do this:

for x in data1:
    *lines*

for y in data2:
    *lines*

into a single loop like this (x is row from data1 and y is row from data2 only):

for x,y in data1,data2:
    *lines*

is this possible? I want to fit and then predict Naive Bayes data in a single loop:

# group data by prodi
for no, dfx_prodi in dfx.groupby('prodi'):
    # implement naive bayes fit data
    bnb.fit(dfx_prodi[var], dfx_prodi['daftar_kembali'])

for no, dfy_prodi in dfy.groupby('prodi'):
    # implement naive bayes predict data
    y_pred = bnb.predict(dfy_prodi[var])

It works, but the result seem fishy, are there any way to do it in one loop while keeping the groupby?


Solution

  • Unless I misunderstood something, you can just use the zip function, for example as

    for x,y in zip(x_list,y_list):
        print(x,y)
    

    In your case this should be something like

    for (no, dfx_prodi), (no, dfy_prodi) in zip(dfx.groupby('prodi'), dfy.groupby('prodi')):
        # implement naive bayes fit data
        bnb.fit(dfx_prodi[var], dfx_prodi['daftar_kembali'])
        y_pred = bnb.predict(dfy_prodi[var])