这是我的数据帧:
user1 user2 cat quantity + other quantities
----------------------------------------------------
Alice Bob 0 ....
Alice Bob 1 ....
Alice Bob 2 ....
Alice Carol 0 ....
Alice Carol 2 ....
我想确保每个user1-user2
对都有一行对应于每个类别(有三个:0,1,2)。如果不是,我想插入一行,并将其他列设置为零。你知道吗
user1 user2 cat quantity + other quantities
----------------------------------------------------
Alice Bob 0 ....
Alice Bob 1 ....
Alice Bob 2 ....
Alice Carol 0 ....
Alice Carol 1 <SET ALL TO ZERO>
Alice Carol 2 ....
到目前为止,我得到的是所有user1-user2
的列表,其中cat
的值少于3个:
df.groupby(['user1','user2']).agg({'cat':'count'}).reset_index()[['user1','user2']]
我可以迭代这些用户,但这需要很长时间(有超过100万对这样的用户)。我已经检查过基于某些条件(如Pandas/Python adding row based on condition和Insert row in Pandas Dataframe based on a condition)在pandas中插入行的其他解决方案,但它们并不完全相同。你知道吗
此外,由于这是一个巨大的数据集,解决方案必须矢量化。我该怎么办?你知道吗
通过^{} 将^{} 与^{} 一起使用:
另一种解决方案是通过列的唯一值和带有
right
连接的merge
的所有组合来创建新的Dataframe
:编辑2:
编辑3:
相关问题 更多 >
编程相关推荐