我想使用pandas在python中构建一个调度应用程序。你知道吗
下面的数据帧是初始化的,其中0
表示一个人是否忙,1
表示一个人是否有空。你知道吗
import pandas as pd
df = pd.DataFrame({'01.01.': [1,1,0], '02.01.': [0,1,1], '03.01.': [1,0,1]}, index=['Person A', 'Person B', 'Person C'])
>>> df
01.01. 02.01. 03.01.
Person A 1 0 1
Person B 1 1 0
Person C 0 1 1
我现在想随机安排n
每天的人数,如果他们有空的话。换句话说,对于每天,如果有人(1
),则随机设置n
计划人数(2
)。你知道吗
我尝试了以下方法:
# Required number of people across time / columns
required_number = [0, 1, 2]
# Iterate through time / columns
for col in range(len(df.columns)):
# Current number of scheduled people
current_number = (df.iloc[:, [col]].values==2).sum()
# Iterate through indices / rows / people
for ind in range(len(df.index)):
# Check if they are available (1) and
# if the required number of people has not been met yet
if (df.iloc[ind, col]==1 and
current_number<required_number[col]):
# Change "free" / 1 person to "scheduled" / 2
df.iloc[ind, col] = 2
# Increment scheduled people by one
current_number += 1
>>> df
01.01. 02.01. 03.01.
Person A 1 0 2
Person B 1 2 0
Person C 0 1 2
这是预期的,但是-因为我只是循环,我没有办法添加随机性(即Person A / B / C
)是随机选择的,只要它们是可用的。有没有一种直接在熊猫身上这样做的方法?你知道吗
谢谢。麻栎
您可以在序列中随机选择适当的索引,然后更改与所选索引对应的值:
现在
df
是想要的结果。你知道吗相关问题 更多 >
编程相关推荐