gpt4 book ai didi

python - 根据其他列中唯一值的长度在 Pandas 中创建一个新列

转载 作者:太空宇宙 更新时间:2023-11-04 07:15:15 25 4
gpt4 key购买 nike

我有一个数据框如下:

df

id val
0 1 21
1 2 35
2 2 45
3 3 55
4 1 10
5 4 90
6 3 45
7 2 78
8 3 23

我想根据 id 中每个值的长度创建一个新列 cat

如果 len(id) <= 1 cat 中的值应该是 'A'

如果 len(id) < 3 值应该是 'B'

如果 len(id) >= 3 值应该是 'C'

预期输出:

    id   val   cat
0 1 21 B
1 2 35 C
2 2 45 C
3 3 55 C
4 1 10 B
5 4 90 A
6 3 45 C
7 2 78 C
8 3 23 C

我尝试过的:

def test(series):
if len(series) <= 1:
return 'A'
elif len(series) < 3:
return 'B'
else:
return 'C'


df.groupby('id').apply(test)

以上代码错误:

TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed

最佳答案

您可以使用mapvalue_countspd.cut:

 df['cat'] = df.id.map(pd.cut(df.id.value_counts(),
bins=[0,1,2,np.inf],
labels=['A','B','C']))

输出:

   id  val cat
0 1 21 B
1 2 35 C
2 2 45 C
3 3 55 C
4 1 10 B
5 4 90 A
6 3 45 C
7 2 78 C
8 3 23 C

关于python - 根据其他列中唯一值的长度在 Pandas 中创建一个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49497627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com