python - 使用pivot_table时同时对aggfunc应用两个numpy函数

标签 python pandas numpy dataframe

我有这张表:

user_id | datetime   | type
1       | 2015-01-01 | 1
1       | 2015-01-01 | 2
1       | 2015-01-01 | 2
1       | 2015-01-02 | 2
2       | 2015-01-01 | 2
2       | 2015-01-02 | 1
2       | 2015-01-02 | 2

我有这个pivot_table代码:

df = df.pivot_table('type', ['user_id'], ['datetime'], aggfunc=np.mean)

但是,我想同时应用两个 unique().sum() 函数来满足此条件,而不是 np.mean:

If there are both 1 and 2 during specific days per user, then I want to put 3, if there is only 1 for a specific day I want to put 2, etc.

例如,所需的输出如下:

user_id | 2015-01-01 | 2015-01-02 
1       | 3          | 2 
2       | 2          | 3 

有什么想法吗?

最佳答案

这是你想要的吗?

In [50]: df.pivot_table('type', ['user_id'], ['datetime'], aggfunc=lambda x: x.unique().sum())
Out[50]:
datetime  2015-01-01  2015-01-02
user_id
1                  3           2
2                  2           3

关于python - 使用pivot_table时同时对aggfunc应用两个numpy函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41916460/

相关文章:

python - Pandas 有条件地创建系列/数据框列

python - 如何对OpenCV calcHist()直方图进行polyfit()?

python - 如何在Python中的同一页面中绘制Excel数据的多个图表

python - 使用 numpy 或其他库在 python 中进行列表扩充

python - 在 pandas dataframe 数组中加载乘法 csv,并以索引作为文件名

python - 成对融化在 pandas 数据框中

python-3.x - 限制异常值

python - 追加到 Pandas 多重索引

python - 在 Django 中发出 POST 请求后无法进行简单的重定向(使用 HttpResponseRedirect)

python - 具有神经网络思维模式的简单逻辑回归