使用python/pandas的仪表板概念

2024-05-16 04:04:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须开发一个带有“可定制”指标的仪表板,并从多个csv文件提交数据。 这将与Django一起开发。我首先查找Django包,但没有找到任何有用的包

但我不知道如何进行

我开始学习pandas library,它非常酷,但我的问题之一是我必须按照模型格式化仪表板

我的想法是在python模型中定义指标存储,并在该模型上循环以计算指标并生成仪表板

例如,指标可定义如下:

indicators = [
    {
        'id': 1,
        'type': 'recruitement',         # header in pivot table
        'label': 'Randomized all, N',   # indicator label
        'value': ['number',],           # indicator expected result format
        'filter': None,                 # indicator filter to apply
        'source': 'crf_ran',            # indicator csv files source for calculating
    },
    {
        'id': 2,
        'type': 'recruitement',
        'label': 'Sex (Woman), %',
        'value': ['pourcentage',],
        'filter': 'sex == 2',
        'source': 'crf_ran',    
    },
    {
        'id': 3,
        'type': 'Follow up',
        'label': 'D7 visits: N performed (% performed/expected)',
        'value': ['number','pourcentage',],
        'filter': 'timing == 7',
        'source': 'crf_vis',    
    },
]

源数据#1(crf#u ran.csv):

record_id,country,pat,sex,age,hiv
1,Ivory Coast,CIV-TR-001,2,51,'positive'
2,Ivory Coast,CIV-SM-002,1,33,'negative'
...

源数据#2(crf#u vis.csv):

record_id,pat,timing,date
1,CIV-SM-001,7,15/01/2021
2,CIV-SM-001,14,21/01/2021
...

预期输出为csv

'type',indicator','Total','Ivory Coast','South Africa'
'Recruitement','Randomized all, N',99,51,48
'Recruitement','Sex (Woman), %',72,70,74
'Follow up','D7 visits: N performed (% performed/expected)','10 (90)','6 (100)','3 (75)'
...

预期输出为xls

Report date: 20/07/2021
                                           Total    Ivory Coast   South Africa
Recruitement
Randomized all, N                             99             51             48
Sex (Woman), %                                72             70             74
Follow up
D7 visits: N performed (% performed/expected) 10 (90)         6 (100)        3 (75)
...

但用熊猫来计算我使用的第二个指标“性别(女性)%”

country_grp = df.groupby(['country'])
country_grp['sex'].value_counts(normalize=True)

并获得以下输出

country       sex
Ivory Coast   1      0.632653
              2      0.367347
South Africa  1      0.509804
              2      0.490196
Name: sex, dtype: float64

我还尝试像这样使用pivot_表:

sex_filt = df['sex'] == 2
pivot_count = df[sex_filt].pivot_table(values="pat", index='sex', columns='country', aggfunc=len).rename(index={2:'Sex (Woman), %'})
pivot_count.to_csv('dashboard.csv', mode='a', header=False)

并在csv文件中获得以下结果:

"Sex (Woman), %",24,19

直到现在,我还没有找到如何继续编写一个可定制的仪表板。。。 也许我是错的,我打算和熊猫一起做


Tags: csvidtype仪表板指标countryindicatorpivot