计算熊猫数据框中的摘要行

时间:2019-02-06 07:43:37

标签: python pandas python-2.7

这是我到目前为止创建的(Pandas DataFrame): 代码:

table = pd.pivot_table(df1, index=['Assignee', 'IssueType'], columns=['Status'], values='Key', aggfunc={'Key': np.count_nonzero}, dropna=True)
table['Total'] = table.sum(axis=1)
table = table.fillna(0)
table = table.apply(pd.to_numeric, errors='ignore')
table = table.astype(int)
table.to_csv(output_file_path, sep=delimiter)

输出:

Assignee~IssueType~Analysis~Blocked~Closed~Done~In Progress~Open~Ready For QA Testing~Total
Smith, John~Story~0~0~0~0~0~1~0~1
Smith, John~Sub-task~0~0~0~0~0~1~0~1
Smith, John~Task~0~0~0~0~2~5~0~7
Doe, Jane~Bug~0~0~0~0~1~0~0~1
Polo, Marco~Bug~0~0~0~0~0~2~0~2
Polo, Marco~Story~0~0~1~0~0~0~0~1
Polo, Marco~Task~1~0~0~0~4~2~0~7

这就是我想要的(考虑到我可以有数字/非数字列:

Assignee~IssueType~Analysis~Blocked~Closed~Done~In Progress~Open~Ready For QA Testing~Total
    Smith, John~Story~0~0~0~0~0~1~0~1
    Smith, John~Sub-task~0~0~0~0~0~1~0~1
    Smith, John~Task~0~0~0~0~2~5~0~7
    Doe, Jane~Bug~0~0~0~0~1~0~0~1
    Polo, Marco~Bug~0~0~0~0~0~2~0~2
    Polo, Marco~Story~0~0~1~0~0~0~0~1
    Polo, Marco~Task~1~0~0~0~4~2~0~7
**GrandTotal~GrandTotal~1~0~1~0~7~11~0~20**

使用Pandas DataFrames实现此目的的最佳/最佳方式是什么? 提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这是我对这个问题的回答。也许还有改进的余地(但至少我满意)。

def append_summary_total(df_index, file_path, delimiter):
    file_path = os.path.abspath(file_path)
    delimiter = str(delimiter)
    df = pd.read_csv(file_path, sep=delimiter)
    sums = df.select_dtypes(pd.np.number).sum().rename('Grand Total')
    df.loc['Grand Total'] = df.select_dtypes(pd.np.number).sum()
    df = df.fillna("GrandTotal")
    df = df.set_index(df_index)
    df = df.apply(pd.to_numeric, errors='ignore')
    df = df.astype(int)
    df.to_csv(file_path, sep=delimiter)

这是输出: Sample Output