I Need Fix In Code

Joined
Apr 12, 2023
Messages
1
Reaction score
0
Hello friends. Below is a code I use. As you can see in this code, when you enter a "Kume" (means cluster), it performs the necessary calculations and gives you the result as an excel output. Now, instead of entering many "clusters" one by one, for example, let me list 20 "clusters" there, and output them all in a single excel sheet as columns.. The code needs to be made to do this. I would be very happy if you could help with this. By the way, the existing code has a function like this, when you write many "clusters" there, it treats them as a whole and calculates. It is necessary to take this situation into account when making corrections. I wish everyone a happy day.

from itertools import combinations
import pandas as pd
import numpy as np
from google.colab import files

# Veriler------------------------------
# Sadece aşağıdaki rakamlar ve çift tek kısımları değişltirilecek.
# Sonra yukarıdaki menüde Çalışma Zamanı --> Tümünü Çalıştır.

kume_1 = [ [17,3,6,1,2,4], "cift"]
# -------------------------------------

tum_kumeler = [kume_1]
kullanilan_sayilar = []
for kume in tum_kumeler:
for sayi in kume[0]:
if sayi not in kullanilan_sayilar:
kullanilan_sayilar.append(sayi)
kullanilan_sayilar.sort()
print("Kullanılan Sayılar: ",kullanilan_sayilar )

def sub_lists (l):
comb = []
for i in range(len(l)+1):
comb += [list(j) for j in combinations(l, i)]
return comb[1:]

def conver_str(l):
result_list = []

for x in l:
string = ""
for y in x:
string +=str(y) + ','
result_list.append(string[:-1])

return (result_list)

df = pd.DataFrame(columns = ["Küme 1 " + kume_1[1]],
index = conver_str(sub_lists(kullanilan_sayilar)))
df.head(5)

for x in range(len(df.index)):
for y in range(len(df.columns)):
sum = 0
for z in df.index[x].split(','):
sum += tum_kumeler[y][0].count(int(z))
df.iloc[x,y] = sum
df.head(5)

df_result = pd.DataFrame(index = df.index,
columns = list(df.columns) + ["Sonuç"])
for row in df.index:
for col in df.columns:
if (df.loc[row, col] % 2 == 0 and col[-1] == "t") or (df.loc[row, col] % 2 != 0 and col[-1] == "k"):
df_result.loc[row,col] = 'P'
else:
df_result.loc[row,col] = 'N'

row_result = list(df_result.loc[row])

if row_result.count('P') == 1:
df_result.loc[row, "Sonuç"] = 'A'

if row_result.count('N') == 4:
df_result.loc[row, "Sonuç"] = 'B'


df_result.sort_values(by=['Sonuç']).head()
 
Joined
Mar 31, 2023
Messages
95
Reaction score
8
To modify the code to handle multiple clusters and output them all in a single Excel sheet as columns, you can follow these steps:

  1. Remove the existing kume_1 list and replace it with a list of multiple clusters, each represented by a list of numbers and a string indicating whether it is "cift" or "tek".
  2. Modify the loop that extracts the kullanilan_sayilar list to handle multiple clusters.
  3. Modify the loop that creates the df dataframe to use the cluster number as part of the column name.
  4. Modify the loop that calculates the results to handle multiple clusters and output them as columns in the df_result dataframe.
  5. Python:
    from itertools import combinations
    import pandas as pd
    import numpy as np
    from google.colab import files
    
    tum_kumeler = [
        [[17,3,6,1,2,4], "cift"],
        [[8, 9, 2, 10], "tek"],
        [[1, 2, 3, 4, 5], "tek"],
        [[6, 7, 8, 9, 10], "cift"]
    ]
    
    kullanilan_sayilar = []
    for kume in tum_kumeler:
        for sayi in kume[0]:
            if sayi not in kullanilan_sayilar:
                kullanilan_sayilar.append(sayi)
    kullanilan_sayilar.sort()
    print("Kullanılan Sayılar: ",kullanilan_sayilar )
    
    def sub_lists(l):
        comb = []
        for i in range(len(l)+1):
            comb += [list(j) for j in combinations(l, i)]
        return comb[1:]
    
    def conver_str(l):
        result_list = []
        for x in l:
            string = ""
            for y in x:
                string +=str(y) + ','
            result_list.append(string[:-1])
        return (result_list)
    
    dfs = []
    for i, kume in enumerate(tum_kumeler):
        df = pd.DataFrame(columns=["Küme " + str(i+1) + " " + kume[1]],
                          index=conver_str(sub_lists(kullanilan_sayilar)))
        for x in range(len(df.index)):
            for y in range(len(df.columns)):
                total = 0
                for z in df.index[x].split(','):
                    total += kume[0].count(int(z))
                df.iloc[x, y] = total
        df_result = pd.DataFrame(index=df.index,
                                 columns=list(df.columns)+["Sonuç"])
        for row in df.index:
            for col in df.columns:
                if (df.loc[row, col] % 2 == 0 and col[-1] == "t") or (df.loc[row, col] % 2 != 0 and col[-1] == "k"):
                    df_result.loc[row,col] = 'P'
                else:
                    df_result.loc[row,col] = 'N'
            row_result = list(df_result.loc[row])
            if row_result.count('P') == 1:
                df_result.loc[row, "Sonuç"] = 'A'
            if row_result.count('N') == 4:
                df_result.loc[row, "Sonuç"] = 'B'
        dfs.append(df_result)
    
    result_df = pd.concat(dfs, axis=1)
    
    result_df.to_excel("result.xlsx")
    files.download("result.xlsx")
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top