Transforming a Pandas DataFrame to a New Structure with Specific Columns

I am working with a pandas DataFrame that contains data structured in a certain way. I need to transform it to a new structure with the following columns:

my desired output

indicator name dimension type dimension date value company
Number of Vehicles all policies all 1 Nrta
Number of Vehicles by channel Aggregators 1 Nrta
Number of Vehicles by channel Non-Aggregators 0 Nrta
Number of Vehicles by gender Male 0 Nrta
Number of Vehicles by gender Female 0 Nrta

my_current_file

I have started to write a function to transform the DataFrame, but I need help to adjust it so that it matches the desired output format.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def transform_table(df):
# Check if the DataFrame is valid or has the expected structure
if df.empty or df.shape[1] < 10:
print("DataFrame is empty or does not have enough columns.")
return pd.DataFrame() # Return an empty DataFrame if input is invalid
# Extract the company name and other data
company_name = df.iloc[0, 2] # Get the company name from the first row, third column
# Create a list to store the output data
out_data = []
out_data.append(['indicator name', 'channels', 'gender', 'region', 'age', 'date', 'value', 'company'])
# Loop through the rows (starting from row 6 in the original array, which is index 5 in 0-based indexing)
for idx, row in df.iloc[5:0].iterrows():
for v in range(0, 3): # Loop through the 3 quarters
out_data.append([
"Number of Vehicles", row[5], row[4], row[2], row[1], df.iloc[3, 6 + v * 4], df.iloc[idx, 6 + v * 4], company_name
])
out_data.append([
"Total Premium excluding commission", row[5], row[4], row[2], row[1],df.iloc[3, 6 + v * 4], df.iloc[idx, 7 + v * 4], company_name
])
out_data.append([
"Commission amount", row[5], row[4], row[2], row[1], df.iloc[3, 6 + v * 4], df.iloc[idx, 8 + v * 4], company_name
])
out_data.append([
"Total Premium including commission", row[5], row[4], row[2], row[1], df.iloc[3, 6 + v * 4], df.iloc[idx, 9 + v * 4], company_name
])
return pd.DataFrame(out_data)
</code>
<code>def transform_table(df): # Check if the DataFrame is valid or has the expected structure if df.empty or df.shape[1] < 10: print("DataFrame is empty or does not have enough columns.") return pd.DataFrame() # Return an empty DataFrame if input is invalid # Extract the company name and other data company_name = df.iloc[0, 2] # Get the company name from the first row, third column # Create a list to store the output data out_data = [] out_data.append(['indicator name', 'channels', 'gender', 'region', 'age', 'date', 'value', 'company']) # Loop through the rows (starting from row 6 in the original array, which is index 5 in 0-based indexing) for idx, row in df.iloc[5:0].iterrows(): for v in range(0, 3): # Loop through the 3 quarters out_data.append([ "Number of Vehicles", row[5], row[4], row[2], row[1], df.iloc[3, 6 + v * 4], df.iloc[idx, 6 + v * 4], company_name ]) out_data.append([ "Total Premium excluding commission", row[5], row[4], row[2], row[1],df.iloc[3, 6 + v * 4], df.iloc[idx, 7 + v * 4], company_name ]) out_data.append([ "Commission amount", row[5], row[4], row[2], row[1], df.iloc[3, 6 + v * 4], df.iloc[idx, 8 + v * 4], company_name ]) out_data.append([ "Total Premium including commission", row[5], row[4], row[2], row[1], df.iloc[3, 6 + v * 4], df.iloc[idx, 9 + v * 4], company_name ]) return pd.DataFrame(out_data) </code>
def transform_table(df):
    # Check if the DataFrame is valid or has the expected structure
    if df.empty or df.shape[1] < 10:
        print("DataFrame is empty or does not have enough columns.")
        return pd.DataFrame()  # Return an empty DataFrame if input is invalid

    # Extract the company name and other data
    company_name = df.iloc[0, 2]  # Get the company name from the first row, third column

    # Create a list to store the output data
    out_data = []
    out_data.append(['indicator name', 'channels', 'gender', 'region', 'age', 'date', 'value', 'company'])

    # Loop through the rows (starting from row 6 in the original array, which is index 5 in 0-based indexing)
    for idx, row in df.iloc[5:0].iterrows():
        for v in range(0, 3):  # Loop through the 3 quarters
            out_data.append([
                "Number of Vehicles", row[5], row[4], row[2], row[1], df.iloc[3, 6 + v * 4], df.iloc[idx, 6 + v * 4], company_name
            ])
            out_data.append([
                "Total Premium excluding commission", row[5], row[4], row[2], row[1],df.iloc[3, 6 + v * 4], df.iloc[idx, 7 + v * 4], company_name
            ])
            out_data.append([
                "Commission amount", row[5], row[4], row[2], row[1], df.iloc[3, 6 + v * 4], df.iloc[idx, 8 + v * 4], company_name
            ])
            out_data.append([
                "Total Premium including commission", row[5], row[4], row[2], row[1], df.iloc[3, 6 + v * 4], df.iloc[idx, 9 + v * 4], company_name
            ])

    return pd.DataFrame(out_data) 

the ouput from the code above

indicator name channels gender region age date value company
Number of Vehicles Aggregators 6/30/2024 1 Nrta
Number of Vehicles Non-Aggregators 6/30/2024 0 Nrta

Question:
How can I adjust my existing code to produce the desired output format? Any suggestions to help achieve this transformation effectively would be greatly appreciated!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật