[英]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.