[英]Pivot table with list entries pandas data frame
I have a data frame that has entries that look like this:我有一个数据框,其中的条目如下所示:
customer_id products_purchased
1 A,B,D,Q
2 B,K,T
3 A
4 M,H,U,R,T,Z
1 A,U,C
3 P,T
.
.
.
I would like to produce a pivot table that has the customer_id and then a column for each product and a count (0, if the customer never purchased the product).我想生成一个数据透视表,其中包含 customer_id,然后是每个产品的列和计数(如果客户从未购买过该产品,则为 0)。 For the example above:对于上面的例子:
customer_id A B C D H K M P Q R T U Z
1 2 1 1 1 0 0 0 0 1 0 0 1 0
2 0 1 0 0 0 1 0 0 0 0 1 0 0
3 1 0 0 0 0 0 0 1 0 0 1 0 0
4 0 0 0 0 1 0 1 0 0 1 1 1 0
There is also a datetime column to indicate when the purchase was made, but it is not important to this particular problem.还有一个日期时间列来指示购买的时间,但这对于这个特定问题并不重要。
This is str.get_dummies
then groupby:这是str.get_dummies
然后是 groupby:
(df['products_purchased'].str.get_dummies(',')
.groupby(df['customer_id']).sum()
.reset_index()
)
Output:输出:
customer_id A B C D H K M P Q R T U Z
0 1 2 1 1 1 0 0 0 0 1 0 0 1 0
1 2 0 1 0 0 0 1 0 0 0 0 1 0 0
2 3 1 0 0 0 0 0 0 1 0 0 1 0 0
3 4 0 0 0 0 1 0 1 0 0 1 1 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.