![](/img/trans.png)
[英]How to create a new column based on calculations made in other columns in PySpark
[英]Create a new column based on other column and calculations
這是我的數據框: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”創建一個新列“得分”。 條件是:
最后,預期結果是:
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
謝謝你的幫助。
在eval
使用np.select
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
使用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/genic/pandas.Series.apply.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.