python - 将数据框中多列的数据分组到摘要视图中
问题描述
我有一个如下数据框,并希望创建如图所示的摘要信息。你能帮忙在熊猫中如何做到这一点。
数据框:
import pandas as pd
ds = pd.DataFrame(
[{"id":"1","owner":"A","delivery":"1-Jan","priority":"High","exception":"No Bill"},{"id":"2","owner":"A","delivery":"2-Jan","priority":"Medium","exception":""},{"id":"3","owner":"B","delivery":"1-Jan","priority":"High","exception":"No Bill"},{"id":"4","owner":"B","delivery":"1-Jan","priority":"High","exception":"No Bill"},{"id":"5","owner":"C","delivery":"1-Jan","priority":"High","exception":""},{"id":"6","owner":"C","delivery":"2-Jan","priority":"High","exception":""},{"id":"7","owner":"C","delivery":"","priority":"High","exception":""}]
)
结果:
解决方案
采用:
#crosstab and rename empty string column
df = pd.crosstab(ds['owner'], ds['delivery']).rename(columns={'':'No delivery Date'})
#change positions of columns - first one to last one
df = df[df.columns[1:].tolist() + df.columns[:1].tolist()]
#get counts by comparing and sum of True values
df['high_count'] = ds['priority'].eq('High').groupby(ds['owner']).sum().astype(int)
df['exception_count'] = ds['exception'].eq('No Bill').groupby(ds['owner']).sum().astype(int)
#convert id to string and join with ,
df['ids'] = ds['id'].astype(str).groupby(ds['owner']).agg(','.join)
#index to column
df = df.reset_index()
#reove index name delivery
df.columns.name = None
print (df)
owner 1-Jan 2-Jan No delivery Date high_count exception_count ids
0 A 1 1 0 1 1 1,2
1 B 2 0 0 2 2 3,4
2 C 1 1 1 3 0 5,6,7
推荐阅读
- c - 使用 C 程序读取文本文件导致处理器以 100% 运行
- c++ - 这些指针如何不仅仅指向一个字符或一个字节?
- python - 视图 blog.views.BlogViews 没有返回 HttpResponse 对象。它返回 None 而不是
- npm - package.json 中的安装后脚本
- python - 如何从python中的父文件夹导入依赖的cython模块
- c - 如果条件在 c 中有效,为什么要在里面 printf?
- javascript - 如何解决“功能预部署错误:命令以非零退出代码 126 终止”
- npm - 窗口无法打开 ElectronNET/Electron.NET 应用程序
- android - 如何在 Android 继承的 Activity 类中创建 Handler 和 Runnable 对象
- php - 有没有人有使用 php yii 应用程序的 G Suite SSO 的经验?