你好呀!我有兩個不同的資料幀,我嘗試使用使用這兩個資料幀的函式來獲取 DF1 上的點數超過 DF2 的結果,但是如果另一個資料幀中沒有人的點數,它將除以 1。
我嘗試使用應用函式,但無法在同一個函式中關聯兩個資料幀。
DF1
Person Points
0 Person_1 25
1 Person_2 20
2 Person_3 14
3 Person_4 23
4 Person_5 40
DF2
Person Points
0 Person_1 10
1 Person_2 40
2 Person_3 2
預期輸出:
DF_TOTAL
Person Points
0 Person_1 2.5
1 Person_2 0.5
2 Person_3 7
3 Person_4 23
4 Person_5 40
uj5u.com熱心網友回復:
將Person列設定為兩個 DataFrame 的索引,因此通過對齊/匹配Person值來完成除法(無論行的順序如何)。df1然后用適當的值填充 NaN 值( 的額外行)。
df_total = (
df1.set_index('Person')
.div(df2.set_index('Person'))
.fillna(df1.set_index('Person'))
.reset_index()
)
輸出:
>>> df_total
Person Points
0 Person_1 2.5
1 Person_2 0.5
2 Person_3 7.0
3 Person_4 23.0
4 Person_5 40.0
uj5u.com熱心網友回復:
df2 = df2.reindex(df1.index) #reindex to have df2 same lenght than df1
df2 = df2.fillna(1) #fill NaN values with 1
df1['Points'] = df1['Points'] / df2['Points'] #then divide
df1
| 指數 | 人 | 積分 |
|---|---|---|
| 0 | 人_1 | 2.5 |
| 1 | 人_2 | 0.5 |
| 2 | 人_3 | 7.0 |
| 3 | Person_4 | 23.0 |
| 4 | 人_5 | 40.0 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/484910.html
上一篇:將一個資料框中的百分比應用于其他資料框中的列以創建新資料框
下一篇:指向成員函式的指標有什么意義?
