熊猫:计算两列的不同组合并添加到同一数据帧
问题描述:
需要将两列的唯一组合添加到熊猫中同一数据帧的帮助。 我想要那个“nos”列。熊猫:计算两列的不同组合并添加到同一数据帧
Input:
id acct_nos name
1 1a one
1 1a two
2 2b three
3 3a four
3 3b five
3 3c six
3 3d seven
这里是输出欲:
Output:
id acct_nos nos name
1 1a 1 one
1 1a 1 two
2 2b 1 three
3 3a 4 four
3 3b 4 five
3 3c 4 six
3 3d 4 seven
在上面的例子 ID = 1仅具有1 acct_nos-1a上的nos必须具有值1 ID = 3具有只有4个acct_nos-3a到3d所以nos必须有一个值4.
不知道如何把它放在Python Pandas中。我可以找出SQL查询。
感谢
答
选项1
df.assign(nos=df.id.map(df.drop_duplicates(['id', 'acct_nos']).id.value_counts()))
选项2
使用Counter
from collections import Counter
tups = pd.unique(
zip(df.id.values.tolist(), df.acct_nos.values.tolist())
).tolist()
df.assign(nos=df.id.map(Counter([tup[0] for tup in tups])))
id acct_nos name nos
0 1 1a one 1
1 1 1a two 1
2 2 2b three 1
3 3 3a four 4
4 3 3b five 4
5 3 3c six 4
6 3 3d seven 4
+0
谢谢您花时间回答此问题。我从来没有想过有这么多的选择。 – Arpit
+0
@Arpit没有问题,我认为显示解决同一问题的多种方法非常重要。 – piRSquared
谢谢You.It工作。 – Arpit