gpt4 book ai didi

python - 如何根据 Pandas 中其他两列的值计算一列的计数?

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

我有一个包含三列的数据集:

import pandas as pd

df = pd.DataFrame({'A': [1,2,3,2,3,3],
'B': [1.0, 2.0, 3.0, 2.0, 3.0, 3.0],
'C': [0.0, 3.5, 1.2, 2.1, 3.1, 0.0]})

现在,显然我可以使用 df['A'].value_counts()让我得到 A 列中值的计数:

df['A'].value_counts()
3 3
2 2
1 1
Name: A, dtype: int64

但是,我需要的是能够根据 B 之间的关系更改计数值。和 C .

例如:

df['B'][0] - df['C'][0]
1.0
df['B'][1] - df['C'][1]
-1.5

我的情况是,我想要总和 > 0算作 1,求和 < 0计为-1,和0算作 0。

所以为了我的目的,有 BC变成这样:

df = pd.DataFrame({'A':      [1,  2, 3,  2,  3, 3],
'counts': [1, -1, 1, -1, -1, 1]})

然后以某种方式能够将其转化为:

3  2
1 1
2 -2

是我所追求的。我将如何使用 Pandas 来做到这一点?

最佳答案

import pandas as pd
import numpy as np

df['counts'] = np.sign(df.B - df.C) # use the numpy.sign to create the count column
df.groupby('A')['counts'].sum() # group the counts by column A and sum the value

#A
#1 1.0
#2 -2.0
#3 1.0
#Name: counts, dtype: float64

关于python - 如何根据 Pandas 中其他两列的值计算一列的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38877338/

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