[Python] How can I add an element directly under a specific column without inserting a new row?

Discussão em 'Python' iniciado por Stack, Abril 4, 2025.

  1. Stack

    Stack Membro Participativo

    I have two lists of same length. I'm iterating through them by using a while loop. One is for colleges (which has duplicates in it) and other is for the courses they offer. I want to add the colleges to columns and their courses to the cells below it. How do I do that? I've tried this:

    import pandas as pd
    df = pd.read_excel(location) # location of the excel file
    colleges = list(df.loc[1:]["Institute"])
    courses = list(df.loc[1:]["Academic Program Name"])
    df = pd.DataFrame()
    i = 0
    while i < len(colleges): # or courses
    if colleges not in df.columns:
    df[colleges] = ""
    df.loc[len(df), colleges] = courses
    i = i + 1
    df.to_excel(location + "Results.xlsx", index=False)


    And I get this error


    PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling 'frame.insert' many times, which has poor performance. Consider joining all columns at once using pdf.concat(axis=1) instead. To get a de-fragmented frame, use 'newframe = frame.copy()'
    ​

    [​IMG][​IMG][​IMG]

    I apologise if this is a silly question. This is the first time I'm working with pandas and for the life of me, I cannot figure it out. Any help will be appreciated. Thank you.

    Continue reading...

Compartilhe esta Página