最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Sorting wire table - Stack Overflow

programmeradmin2浏览0评论

I have a csv field with 4 columns. Now i want to sort the rows with the values form column 2 and 3. The rows stand for wire en column 2 is the first connection point en column 3 is the second connection point. Now i want to search in the csv data for wire bridges and sort this table so i have the same wire bridges among themselves. And group this wires together en place a group number in column 5.

I have the following code:

Input Csv file:

1;-100F3:1;-100F4:1;test
2;-100F4:1;-100F10:2;test
3;-50F4:2;-100F10:2;test
4;-50F5:3;-50F4:3;test
5;-50F4:3;-30F4:3;test
6;-30F4:3;-200F10;test

Python File:

import pandas as pd
import re

# Functie om correct te sorteren
def natural_sort_key(s):
    """Sorteert een string correct op basis van cijfers en letters"""
    return [int(text) if text.lstrip("-").isdigit() else text for text in re.split(r'(-?\d+)', s)]


# Laad het CSV-bestand (vervang 'bestand.csv' door jouw bestandsnaam)
bestand = "bestand.csv"
df = pd.read_csv(bestand)
df = pd.read_csv(bestand, delimiter=";", header=None, names=["ID", "Kolom_2", "Kolom_3", "Omschrijving"])
# Controleer of het bestand de juiste kolommen heeft

print(df.shape)
if df.shape[1] < 3:
    raise ValueError("Het bestand moet minstens 3 kolommen bevatten.")

# Geef kolommen standaardnamen als ze geen headers hebben
df.columns = [f"Kolom_{i+1}" for i in range(df.shape[1])]

# Zorg ervoor dat binnen elke rij Kolom_2 altijd een lagere alfabetische waarde heeft dan Kolom_3
df[['Kolom_2', 'Kolom_3']] = df[['Kolom_2', 'Kolom_3']].apply(lambda x: sorted(x), axis=1, result_type='expand')

# Groeperen op basis van overeenkomsten in Kolom_2 en Kolom_3
df_sorted = df.sort_values(by=["Kolom_2", "Kolom_3"])

# Toon het gegroepeerde resultaat
print(df)  # Toon de DataFrame in de terminal
df.to_csv("output.csv", index=False)  # Opslaan in een CSV-bestand
print("Data opgeslagen in output.csv")

# Groeperen op basis van gedeelde waarden in Kolom_2 en Kolom_3
group_dict = {}
group_counter = 1

# Itereer door de rijen om groepen toe te wijzen
for index, row in df.iterrows():
    found_group = None
    for key, values in group_dict.items():
        if row["Kolom_2"] in values or row["Kolom_3"] in values:
            found_group = key
            break

    if found_group:
        group_dict[found_group].update([row["Kolom_2"], row["Kolom_3"]])
        df.at[index, "Kolom_5"] = found_group
    else:
        group_dict[group_counter] = {row["Kolom_2"], row["Kolom_3"]}
        df.at[index, "Kolom_5"] = group_counter
        group_counter += 1

# Zorg ervoor dat gerelateerde rijen dezelfde groepsnummer krijgen
for key, values in group_dict.items():
    df.loc[df["Kolom_2"].isin(values) | df["Kolom_3"].isin(values), "Kolom_5"] = key

print(df)

Output:

Data opgeslagen in output.csv
   Kolom_1    Kolom_2   Kolom_3 Kolom_4  Kolom_5
0        1   -100F3:1  -100F4:1    test      1.0
1        2  -100F10:2  -100F4:1    test      1.0
2        3  -100F10:2   -50F4:2    test      1.0
3        4    -50F4:3   -50F5:3    test      2.0
4        5    -30F4:3   -50F4:3    test      2.0
5        6    -200F10   -30F4:3    test      2.0

But the sorting is not correctly. I want to be the same value under need each other. Also if the value not in the same column the script need to switch the value from column 2 to 3 of other wise.

I want the following output:

Data opgeslagen in output.csv
   Kolom_1    Kolom_2   Kolom_3 Kolom_4  Kolom_5
0        1   -100F3:1  -100F4:1    test      1.0
1        2  -100F10:2  -100F4:1    test      1.0
2        3  -100F10:2   -50F4:2    test      1.0
3        4    -50F4:3   -50F5:3    test      2.0
4        5    -50F4:3   -30F4:3    test      2.0
5        6    -200F10   -30F4:3    test      2.0

I have maked a custom sort function but this changes anything.

# Functie om numeriek en alfabetisch correct te sorteren
def natural_sort_key(s):
    if isinstance(s, str):  # Alleen strings sorteren
        return [int(text) if text.lstrip("-").isdigit() else text for text in re.split(r'(-?\d+)', s)]
    return s  # Retourneer numerieke waarden zoals ze zijn
发布评论

评论列表(0)

  1. 暂无评论