在熊猫中读取CSV并以所需格式获取输出

时间:2018-09-16 12:06:14

标签: python-3.x pandas

我是csv的新手。我正在读取dictionary文件,并试图将输出作为import pandas as pd df = pd.read_csv('source.csv') my_projects = ['WORLD', 'P&G', 'AVR', 'ABCD', 'Channel', 'Migration'] filtered_projects = df[(df['area'] == 'MY PROJECTS') & (df['name'].isin(my_projects))] filtered_projects['count'] = 1 total_of_each_error = filtered_projects.groupby(['month','name','errors']).sum().reset_index() total_of_each_error['month'] = pd.to_datetime(total_of_each_error['month']).dt.strftime('%B')

['Big', 'Small', 'Monitoring', 'Improvement']

我要计算的事物列表:total_of_each_error

month name errors count 0 February ABCD Big 1 1 February ABCD Monitoring 3 2 February WORLD Small 1 3 February Channel Big 2 4 February Channel Small 1 5 February Channel Monitoring 1 6 February AVR Monitoring 1 7 April WORLD Monitoring 2 8 May Migration Big 1 9 May Migration Monitoring 2 10 June P&G Small 1 11 June P&G Monitoring 1 12 June ABCD Monitoring 1 13 June WORLD Improvement 1 14 July P&G Monitoring 1 15 July ABCD Small 1 16 July ABCD Monitoring 1 数据帧具有:

dictionary

如果一个月没有特定错误,则应填写零。我试图获得的输出是此data = {'WORLD': {'categories': ['February', 'April', 'May', 'June', 'July'], 'series': [{ 'name': 'Big Issue', 'data': [0, 0, 0, 0, 0] # Number of Bigs in those months }, { 'name': 'Small Issue', 'data': [1, 0, 0, 0, 0] # Number of Smalls in those months }, { 'name': 'Monitoring', 'data': [0, 2, 0, 0, 0] # Number of Monitorings in those months }, { 'name': 'Improvement', 'data': [0, 0, 0, 1, 0] # Number of Improvements in those months }] }, 'P&G': {'categories': ['February', 'April', 'May', 'June', 'July'], 'series': [{ 'name': 'Big Issue', 'data': [0, 0, 0, 0, 0] }, { 'name': 'Small Issue', 'data': [0, 0, 0, 1, 0] }, { 'name': 'Monitoring', 'data': [0, 2, 0, 0, 0] }, { 'name': 'Improvement', 'data': [0, 0, 0, 1, 0] }] } }

WORLD

上面显示的预期输出仅适用于P&Gmy_projects。该字典将包含name中的其余元素。应该保留月份顺序和数据。

编辑:在 <p:commandButton id="link" value="E-payment" action="#{controller.ePaymentMethod}" process="@this" update="@form" oncomplete="proceedToPayment('{epaymentVo.epaymentEboCode}','{epaymentVo.token}')"> </p:commandButton>

中更改了错误的值

1 个答案:

答案 0 :(得分:0)

将数据框排序并修改为正确的格式(使用df.groupby.unstack()),然后在数据框上使用to_dict()方法来获得所需的结果。下面的例子。

import numpy as np
import pandas as pd
df = pd.DataFrame(
    data ={'Month': ['Jan','Feb']*5,
           'Issue': ['Big Issue','Monitoring']*5,
           'value': np.arange(30,40)})

df.groupby(['Month','Issue']).count().unstack()
df.to_dict()

    df.to_dict()