[英]How to get the sum of values from one column with the conditional of another column
假设您的数据被加载到 pandas dataframe 中,您可以使用:
# Sample data
labels = ["a", "b", "c", "a, b, c", "b, c"]
df = pd.DataFrame({
"customer_id": [0, 1]*10,
"category": [labels[np.random.randint(0,len(labels ))] for i in range(20)]
})
# Count per group and pivot the rows to columns
df.groupby(['customer_id', 'category']).size().reset_index().pivot_table(
0, ['customer_id'], 'category').fillna(0).rename_axis(
None, axis=1).reset_index()
output:
customer_id a a, b, c b b, c c
0 0 2.0 1.0 1.0 5.0 1.0
1 1 2.0 0.0 4.0 1.0 3.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.