[Python] Group Rows Using Pandas in Python

Discussão em 'Python' iniciado por Stack, Novembro 20, 2024.

  1. Stack

    Stack Membro Participativo

    I am needing to figure out how to group my CSV data. I currently have my data condensed to what is necessary but I'm not sure how to go about grouping. I need to group based on a couple of criteria. I need the data grouped by weight avg weight ranges. 200-299, 300-399, etc. It also needs to be grouped by whether there is a lot desc value. For example, all rows with class value of 'Steers', avg weight between 300-399, and no lot desc value would be one group. Another would be the same, except with a lot desc value.

    It works, but not exactly like I want based on the screenshot I've provided. I am currently getting each group as a separate CSV (which I plan to make into one eventually), but my sorting isn't working exactly like I want. I'm trying to sort it by 'class', 'avg weight', and 'lot desc'. It works for the first two, but not 'lot desc'. I want to have it sorted like the screenshot.

    Here is my current code:

    def calculate() :
    print("Calculate...")
    global dataFrame
    df = dataFrame

    calculationHeaders = ["class", "lot desc", "head count", "avg weight", "avg price"]
    df = df[calculationHeaders]

    rowsToRemove = ["Bred Heifers", "Dairy Cows", "Dairy Heifers", "Dairy Steers", "Dairy/Beef Heifers", "Dairy/Beef Steers", "Heifer Pairs"]
    columnName = "class"
    try:
    for row in rowsToRemove:
    df = df[df[columnName] != row]

    df["lot desc"] = df["lot desc"].fillna("")

    classCategories = ["Bulls", "Steers", "Heifers", "Cow-Calf Pairs", "Cows", "Bred Cows"]
    df["class"] = pd.Categorical(df["class"], categories=classCategories)

    descCategories = ["", "Value Added", "Thin Fleshed", "Guaranteed Open", "Fancy"]
    df["lot desc"] = pd.Categorical(df["lot desc"], categories=descCategories)

    df = df.sort_values(by=["class", "lot desc", "avg weight"])

    grouped = df.groupby("class")
    for classValue, group_df in grouped:
    print(group_df)
    group_df = group_df.sort_values(by=["class", "avg weight", "lot desc"])
    group_df.to_csv(classValue + ".csv")

    df.to_csv("default.csv")
    except Exception as e:
    raise Exception("Calulate error...")


    The screenshot shows what I'm wanting. The highlighted rows are ones with a lot desc value.[​IMG]

    Continue reading...

Compartilhe esta Página