根据其他列和计算创建一个新列

时间:2019-01-14 23:17:33

标签: python pandas math

这是我的数据框: df

ID AU 1 0 2 1 3 2 4 0 5 3 6 4 7 1 8 2 9 5 10 2 11 4 12 1 13 5 14 3

我想通过使用某些条件基于列“ AU”创建一个新列“得分”。条件是:

  1. 如果“ AU” = 0,则“得分”将为0
  2. 如果0 <'AU'<= 4,则“得分”将为(1-AU)*(1-0.5)+0.5
  3. 如果'AU'> 4,则“得分”将为(1-AU)* 0.2 + 0.2

最后期望的结果是:

ID AU分数 1 0 0 2 1 0,5 3 2 0 4 0 0 5 3 -0,5 6 4 -0,4 7 1 0,5 8 2 0 9 5 -0,6 10 2 0 11 4 -0,4 12 1 0,5 13 5 -0,6 14 3 -0,5

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

np.selecteval一起使用

s1=(df.AU>0)&(df.AU<=4)
s2=df.AU>4
df['Score']=np.select([s1,s2],[df.eval('(1-AU)*(1-0.5)+0.5'),df.eval('(1-AU)*0.2+0.2')],default=0)
df
Out[136]: 
    ID  AU  Score
0    1   0    0.0
1    2   1    0.5
2    3   2    0.0
3    4   0    0.0
4    5   3   -0.5
5    6   4   -1.0
6    7   1    0.5
7    8   2    0.0
8    9   5   -0.6
9   10   2    0.0
10  11   4   -1.0
11  12   1    0.5
12  13   5   -0.6
13  14   3   -0.5

答案 1 :(得分:0)

使用apply函数:

import pandas as pd

def computeScore(x):
    assert x >= 0
    if (x == 0):
        return 0
    elif ((x > 0) & (x <= 4)):
        return (1-x)*(1-0.5)+0.5
    return (1-x)*0.2+0.2

d = {'ID': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
     'AU': [0, 1, 2, 0, 3, 4, 1, 2, 5, 2, 4, 2, 5, 4]}
df = pd.DataFrame(data=d)

df["Score"] = pd.Series(df.AU).apply(computeScore)

API参考:https://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.apply.html

相关问题