从pandas df列中选择的函数 [英] Function to select from columns pandas df
本文介绍了从pandas df列中选择的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在熊猫数据框中有这个测试表
i have this test table in pandas dataframe
Leaf_category_id session_id product_id
0 111 1 987
3 111 4 987
4 111 1 741
1 222 2 654
2 333 3 321
我想要的是
for leaf_category_id 111:
结果应该是.
session_id product_id
1 987,741
4 987
类似地,我可以定义一个对所有leaf_category id都执行相同操作的函数,我的表包含更多行,这只是它的快照.
Similarly can i define a function that does the same for all the leaf_category id's, my table contains more rows, it was just a snapshot of it.
推荐答案
您可以使用 boolean indexing
,然后通过评论
print (df.groupby(['Leaf_category_id','session_id'])['product_id']
.apply(lambda x: ','.join(x.astype(str)))
.reset_index())
Leaf_category_id session_id product_id
0 111 1 987,741
1 111 4 987
2 222 2 654
3 333 3 321
或者如果需要Leaf_category_id
DataFrame
中的每个唯一值:
Or if need for each unique value in Leaf_category_id
DataFrame
:
for i in df.Leaf_category_id.unique():
print (df[df.Leaf_category_id == i] \
.groupby('session_id')['product_id'] \
.apply(lambda x: ','.join(x.astype(str))) \
.reset_index())
session_id product_id
0 1 987,741
1 4 987
session_id product_id
0 2 654
session_id product_id
0 3 321
这篇关于从pandas df列中选择的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文