【问题标题】:Calculating a summary row in a pandas dataframe计算熊猫数据框中的摘要行
【发布时间】:2019-06-30 02:50:18
【问题描述】:

这是我迄今为止创建的 (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 实现这一目标的最佳/最佳方式是什么? 提前感谢您的帮助。

【问题讨论】:

  • 请使用空格而不是波浪号来分隔列
  • 好的。那么,如果我更改 sep="\t",解决方案是什么?
  • Pandas 并没有真正的摘要行。也许你可以做类似this.
  • 感谢 Josh Friedlander 和其他所有审阅此问题的人。很抱歉没有注意到标题毫无意义,并感谢您对其进行编辑。

标签: python pandas python-2.7


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-01-28
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    相关资源
    最近更新 更多