python - 如何根据计算条件新建一列?

标签 python pandas dataframe numpy

有两列A和列Aging。需要创建一个名为 simulator 的新列,其条件 (mean+std) 为 A 列。例如,对于所有 Aging==2,simulator 应根据 A 列中的相应值进行计算。

我尝试了下面给出的代码,但是当我更改老化值时,模拟器值不会改变。下面提供的是引用数据和我试过的代码。

# seed the pseudorandom number generator
from numpy.random import seed
from numpy.random import randint
# seed random number generator
seed(1)
# generate some random numbers
x=pd.DataFrame(randint(0, 10, 20),columns=list('A'))
# reset the seed
seed(1)
# generate some random numbers
x['aging']=pd.DataFrame(randint(1,5,20),columns=list('z'))

x['simulator']=np.where(x['aging']==2,x.A.mean()+x.A.std(),0)
x['simulator']=np.where(x['aging']==4,x.A.mean()+x.A.std(),x['simulator'])

最佳答案

np.where 首先评估您的值,然后然后根据条件选择这些值。因此,在这两种情况下,x.A.mean() + x.A.std() 都是在 entire DataFrame 上计算的,并且在每种情况下都是相同的 DataFrame,因此选择的值是相同的。

唯一的区别是该值仅设置为 x['aging']==2x['aging']==4 的行, 视情况而定。

如果您希望该列在每次老化时为mean + std,请使用groupby + transform :

gp = x.groupby('aging')['A']
x['simulator'] = gp.transform('mean') + gp.transform('std')

    A  aging  simulator
0   5      2   7.088436
1   8      4   6.835113
2   9      1   9.041928
3   5      1   9.041928
4   0      4   6.835113
5   0      2   7.088436
6   1      4   6.835113
7   7      2   7.088436
8   6      4   6.835113
9   9      1   9.041928
10  2      1   9.041928
11  4      2   7.088436
12  5      1   9.041928
13  2      4   6.835113
14  4      2   7.088436
15  2      1   9.041928
16  4      3   7.621320
17  7      2   7.088436
18  7      3   7.621320
19  9      1   9.041928

关于python - 如何根据计算条件新建一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65890244/

相关文章:

python - 使用 numpy 读取 Fortran 格式的小 float 文件

python - 访问另一个实例的损坏成员

java - 使用java在spark中的函数之间

python - 仅当列中的特定值是唯一的时,如何替换它?

python - 将 scikit-learn (sklearn) 预测添加到 pandas 数据框

python - 使用 pd.concat 时添加标识原始数据框的列

python - Pandas 0.15 数据帧 : Remove or reset time portion of a datetime64

python - 从二维数据到具有多索引列的一维 Pandas

pandas - 如何在 Pandas 中切片连续和不连续的索引?

python - 如何将数据框中的每一列与另一个数据框 Pandas 中的一行相乘?