![](/img/trans.png)
[英]Pandas, how to compare the value from one row with all other rows in the same column and add it as a new row value in a new column?
[英]Splitting value from one row to other rows in the same column in pandas
我有一個關於 pandas 的問題
我有一個 DataFrame df
任務 ID | 用戶身份 | 小時 |
---|---|---|
123456 | 123456 | 19 |
123456 | 123456 | 鈉 |
123456 | 123456 | 鈉 |
123456 | 123456 | 鈉 |
654321 | 654321 | 10 |
現在我想將第一行中的 19 分成相等的數量,其中 TaskId 和 UserId 相同 19 / 4 = 4.75
這是我想收到的
任務 ID | 用戶身份 | 小時 |
---|---|---|
123456 | 123456 | 4.75 |
123456 | 123456 | 4.75 |
123456 | 123456 | 4.75 |
123456 | 123456 | 4.75 |
... | ... | ... |
我在stackoverflow上找不到任何東西
謝謝你
使用GroupBy.transform
將第一個值除以計數:
g = df.groupby(['TaskId','UserId'])['Hours']
df['Hours'] = g.transform('first').div(g.transform('size'))
print (df)
TaskId UserId Hours
0 123456 123456 4.75
1 123456 123456 4.75
2 123456 123456 4.75
3 123456 123456 4.75
4 654321 654321 10.00
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.