![](/img/trans.png)
[英]ValueError: can only convert an array of size 1 to a Python scalar for Numpy Select
[英]ValueError: can only convert an array of size 1 to a Python scalar
我有一個與這里非常相似的問題:
我確實有一個表格,其中包含一列中的所有員工及其代表。 boss_id 在其他。
employee_id boss_id receive_reports nr_reports
0 46456 175361 False 0
1 104708 29733 False 0
2 120853 41991 False 0
3 142630 171266 True 1
4 72711 198240 False 0
因此,我想要一個表格,我在其中讀取每個員工的所有直接和間接報告的數量(例如,第一層的所有人員均為 0,CEO 最高為 #allemployees)。 在最后幾列中,我可以輕松區分第一級人員和其他所有人。
我想使用 python 並且我一直在用它纏着我的頭很長一段時間。 我確實有一個大致的想法:從第一層的所有人開始,零報告,再上一層等等......
編輯 1
這是我的方法(我也很想知道是否有更好的方法)
我有一個包含所有 level_0 員工的列表。
def sum_reports(current_level):
# pass current level of employees as list
if len(current_level) == 1:
return
else:
next_level = []
#find boss for every employees at current level and add to next level + add to report of this boss 1
for emp in current_level:
tmp_boss = data.loc[data.employee_id == emp, "boss_id"].item()
next_level.append(tmp_boss)
data.loc[(data.employee_id == tmp_boss),"nr_reports"] += 1
sum_reports(next_level)
sum_reports(level_0)
但我確實收到錯誤:
ValueError: Can only compare identically-labeled Series objects
編輯 2
擺脫了添加.item()
更改代碼with tmp_boss = ...
的比較錯誤with tmp_boss = ...
但現在我確實收到另一個錯誤,我無法跟蹤: ValueError: can only convert an array of size 1 to a Python scalar
我可以解決這個問題,執行以下操作:
添加一個檢查,如果老板已經在我的下一個級別(因為有多個報告給同一個人)
並檢查 boss_id 是否為“0”——我用一個條目替換了 CEO 的 NaN。 這實際上導致了轉換錯誤
這是最終的代碼:
#a list of the bosses column as the direct_reports
direct_reports = data.boss_id.tolist()
seen = []
def sum_reports(current_level):
# pass current level of employees as list
if len(current_level) <= 1:
return
else:
next_level = []
#find boss for every employee at current level and add to next level + add 1 to report of this boss
for emp in current_level:
tmp_boss = data.loc[data.employee_id == emp, "boss_id"].item()
seen.append(tmp_boss)
#only if is the last direct report: add boss to the next_level
if direct_reports.count(tmp_boss) == seen.count(tmp_boss) and tmp_boss != 0:
next_level.append(tmp_boss)
# add reports, plus 1 and the reports sofar of the current emp
sofar = data.loc[data.employee_id == emp, "nr_reports"].item()
data.loc[(data.employee_id == tmp_boss),"nr_reports"] += (sofar+1)
sum_reports(next_level)
# level_o is a list of all employees, who don't appear in the boss column
sum_reports(level_0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.