简体   繁体   中英

how to assign different value to dataframe from a list in python

I want to create a roster using python. there are three possible shift, 7 working days and names of staff to be rotated. there can only be max of two staff on a shift and each staff can only have one off day during the week which should never fall on saturday or sunday. After so many try I was able to create the table with the below code but can't randomly have the shift in the order that I want, the random choice is only populating the table with one value from the shift list

import numpy as np
import random
import pandas as pd

shift = ['am', 'pm', 'off']
names = ['ola', 'ade', 'bisi']
days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', ' sunday']
df = pd.DataFrame(np.random.choice(shift), index=names, columns =days) 

Dataframe is working as expected. Although you use random, you've forwarded just one value (as np.random.choice(shift) returns just one value) to the frame, and it is populating all cells with that value.

Luckily, choice accepts one more argument named size that will return np.array of the given size, so with that, your code should look like this:

shift = ['am', 'pm', 'off']
names = ['ola', 'ade', 'bisi']
days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', ' sunday']
df = pd.DataFrame(
    np.random.choice(shift, size=(len(names), len(days)),
    index=names,
    columns=days
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM