【发布时间】:2021-12-07 19:25:19
【问题描述】:
我想使用 for 循环填充数据框。 其中一列是列表。 这个列表在每次迭代开始时都是空的,一个元素被添加或删除。
当我在每次迭代中打印我的列表时,我得到了正确的结果,但是当我打印我的数据框时,我在每一行上都得到了相同的列表:
你看看我的代码,我正在更新的列表是 list_employe。魔术应该发生在最后 3 行,但它没有。
有谁知道为什么列表以一种方式更新,而数据框只记录所有行的最后一次更新
list_employe = []
total_employe = 0
rows=[]
shiftday = example['SHIFT_DATE'].dt.strftime('%Y-%m-%d').unique().tolist()
for i in shiftday:
shift_day = example[example['SHIFT_DATE'] == i]
list_employe_shift = example[example['SHIFT_DATE']==i]['EMPLOYEE_CODE_POS_UPPER'].unique().tolist()
new_employe = 0
end_employe = 0
for k in list_employe_shift:
shift_days_emp = shift_day[shift_day['EMPLOYEE_CODE_POS_UPPER'] == k]
days = shift_days_emp.iloc[0]['last_day']
#print(days)
if k in list_employe:
if days>1:
end_employe= end_employe+1
total_employe = total_employe-1
list_employe.remove(k)
else:
new_employe = new_employe+1
total_employe = total_employe + 1
list_employe.extend([k])
day = i
total_emp = total_employe
new_emp = new_employe
end_emp = end_employe
rows.append([day, total_emp, new_emp, end_emp, list_employe])
print(list_employe)
df = pd.DataFrame(rows, columns=["day", "total_employe", "new_employe", "end_employe", "list_employe"])
【问题讨论】:
-
前五行的打印 list_employe 显示这是我需要的:[276, 281, 31, 263, 245, 15, 775, 267, 178, 274] [276、281、31、263、245、15、775、267、178、274、212、243、229] [276、31、263、245、15、267、178、212、243、229、 295, 2013, 265, 288] [276, 31, 245, 15, 178, 212, 243, 295, 2013, 265, 288, 289] 和我在列 list_employe 上的 df 显示相同的列表每行:[276, 281, 31, 263, 245, 15, 775, 267, 178, 274, 212, 229, 2013, 265, 289, 220, 173, 290, 285, 297, 293, 291, 298 , 294, 299, 300, 304, 303, 305, 306, 308, 309, 307, 310, 311, 312, ...