在pandas中从 Dataframe 创建表

6fe3ivhb  于 2023-05-05  发布在  其他
关注(0)|答案(1)|浏览(148)
6 Months                                     1 Year
                  LDL<100   LDL<70  LDL>50% Reduction         LDL<100   LDL<70  LDL>50% Reduction
Education-only      
Medication Management                       
 ASCVD  
 DM 
 LDL>190    
 Primary Prevention

如何在pandas中创建这样的表,我有一个仅包含教育和药物管理列的数据集。
请分享代码,我试过几个代码没有人看起来像这样.

v8wbuo2f

v8wbuo2f1#

要创建空表,您可以尝试以下代码

import pandas as pd

def create_column_index():
    """ Define the column index """
    return pd.MultiIndex.from_tuples([
        ("6 Months", "LDL<100"),
        ("6 Months", "LDL<70"),
        ("6 Months", "LDL>50% Reduction"),
        ("1 Year", "LDL<100"),
        ("1 Year", "LDL<70"),
        ("1 Year", "LDL>50% Reduction"),
    ])

def create_row_index():
    """ Define the row index """
    return pd.Index([
        "Education-only",
        "Medication Management",
        "ASCVD",
        "DM",
        "LDL>190",
        "Primary Prevention"
    ])

def create_empty_dataframe():
    # create the empty dataframe
    return pd.DataFrame(index=create_row_index(), columns=create_column_index())

df = create_empty_dataframe()
print(df)

然后,您可以使用此代码将数据填充到特定的单元格中

# Fill the data
df.loc["Education-only", ("6 Months", "LDL<100")] = 10
df.loc["Medication Management", ("1 Year", "LDL<70")] = 20
print(df)

相关问题