我正在 pyspark 中撰寫多行陳述句。我有一個資料框“當前”,我按“專業”分組并創建了一個名為“n_students”的新列來計算每個專業的學生人數。然后我想創建另一個名為 prop 的新列,其中我將每個專業的 n_students 人數除以學生總數。學生總數包含在變數 current_students 中。在校學生總數為 2055。您可以在宣告中看到我剛剛使用數字 2055 作為分母。如何將分母更改為變數 current_students 中的計數?
current_students=current.count()
print(current_students)
2055
(
current
.groupBy('major')
.agg(
expr('count(*) AS n_students')
)
.select(
'major', 'n_students',
expr('ROUND(n_students/2055,4) AS prop')
)
.sort('prop', ascending=False)
.show())
----- ---------- ------
|major|n_students| prop|
----- ---------- ------
| BIO| 615|0.2993|
| CSC| 508|0.2472|
| CHM| 405|0.1971|
| MTH| 320|0.1557|
| PHY| 207|0.1007|
----- ---------- ------
我想得到這個精確的輸出,但我不想使用數字 2055 作為我的分母,而是想從變數 current_students 中提取數字。
current_students=current.count()
(
current
.groupBy('major')
.agg(
expr('count(*) AS n_students')
)
.select(
'major', 'n_students',
expr('ROUND(n_students/##CHANGE TO PULL FROM VARIABLE Current_students##,4) AS prop')
)
.sort('prop', ascending=False)
.show())
----- ---------- ------
|major|n_students| prop|
----- ---------- ------
| BIO| 615|0.2993|
| CSC| 508|0.2472|
| CHM| 405|0.1971|
| MTH| 320|0.1557|
| PHY| 207|0.1007|
----- ---------- ------
uj5u.com熱心網友回復:
使用python的字串format()方法在字串中輸入任何變數的值。
current_students = current.count()
func.expr('ROUND(n_students/{0}, 4) AS prop'.format(current_students))
# Column<'ROUND((n_students / 2055), 4) AS `prop`'>
您也可以使用本機func.col&func.lit代替expr
func.round(('n_students' / func.lit(current_students)), 4).alias('prop')
# Column<'round((n_students / 2055), 4) AS `prop`'>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/529133.html
上一篇:將字串正確拆分為陣列陣列
