Arp*_*pit 4 python size count aggregation pandas
需要帮助将两列的唯一组合添加到pandas中的同一数据框中.我想要那个"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
Run Code Online (Sandbox Code Playgroud)
这是我想要的输出:
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
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,Id = 1只有1个acct_nos-1a,因此nos必须具有值1.Id = 3只有4个acct_nos-3a到3d,因此nos必须具有值4.
不知道如何把它放在Python Pandas中.我能搞清楚的SQL查询.
谢谢
您可以使用groupby.transformwith nunique()函数来计算每个id的唯一元素数:
df['nos'] = df.groupby("id")['acct_nos'].transform("nunique")
df
Run Code Online (Sandbox Code Playgroud)
选项1
df.assign(nos=df.id.map(df.drop_duplicates(['id', 'acct_nos']).id.value_counts()))
Run Code Online (Sandbox Code Playgroud)
选项 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2395 次 |
| 最近记录: |