基于一列大小的新列

2024-09-28 21:53:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个新的列'score'/内径尺寸'对于我当前的数据帧

np.random.seed(1234)
test = pd.DataFrame({'id':np.random.randint(1,5,10),
                     'score':np.random.uniform(0,1,10)})

test = test.sort(['id'])

test
   id     score
4   1  0.875933
5   1  0.357817
6   1  0.500995
3   2  0.958139
7   2  0.683463
9   2  0.370251
2   3  0.801872
0   4  0.272593
1   4  0.276464
8   4  0.712702

我希望我的新数据帧是这样的:

   id     score       score/id.size
4   1  0.875933       0.875933 / 3
5   1  0.357817       0.357817 / 3
6   1  0.500995       0.500995 / 3
3   2  0.958139       0.958139 / 3
7   2  0.683463       0.683463 / 3
9   2  0.370251       0.370251 / 3
2   3  0.801872       0.801872 / 1
0   4  0.272593       0.272593 / 3
1   4  0.276464       0.276464 / 3
8   4  0.712702       0.712702 / 3

抱歉,如果这个问题太简单,我是Python新手。你知道吗

谢谢!你知道吗


Tags: 数据testiddataframesize尺寸nprandom
3条回答

在我看来,您需要按id分组并计数,然后将其作为键在新列中执行操作。你知道吗

counts = test.groupby("id").count()
test["score/id.size"] = test.apply(lambda x: x["score"] / float(counts[counts.index==x["id"]].score), axis=1)

test
   id     score  score/id.size
4   1  0.875933       0.291978
5   1  0.357817       0.119272
6   1  0.500995       0.166998
3   2  0.958139       0.319380
7   2  0.683463       0.227821
9   2  0.370251       0.123417
2   3  0.801872       0.801872
0   4  0.272593       0.090864
1   4  0.276464       0.092155
8   4  0.712702       0.237567

这样就可以了:

test['score / id.size'] = test.score / [(test.id == i).sum() for i in test.id]

我认为这个答案比一些已经发布的答案更好地利用了panda的automagic分组和对齐功能,只是分组和除以分组的大小:

test['score_normalized'] = test.groupby('id', group_keys=False).apply(
    lambda g: g['score'] / len(g)
)

test
Out[9]: 
   id     score  score_normalized
4   1  0.875933          0.291978
5   1  0.357817          0.119272
6   1  0.500995          0.166998
3   2  0.958139          0.319380
7   2  0.683463          0.227821
9   2  0.370251          0.123417
2   3  0.801872          0.801872
0   4  0.272593          0.090864
1   4  0.276464          0.092155
8   4  0.712702          0.237567

相关问题 更多 >