我想创建一个随机工具来对名称进行电台轮换: 我有一个具有以下形状的给定数据框:
data = {'Name': ['Tom', 'Mike', 'Carl', 'Juli', 'Tina', 'Wendy'],
'station1': [0, 1, 1, 1, 0, 0],
'station2': [1, 1, 1, 1, 1, 0],
'station3': [1, 1, 1, 1, 1, 1],
'station4': [1, 1, 1, 1, 1, 1],
'station5': [0, 1, 0, 0, 1, 0],
'station6': [1, 1, 0, 1, 1, 0]}
4 倍旋转 = 列表中的 4 个位置
轮换限制: 没有双站,例如每个列表中的第 1 位 没有相互跟随的车站, 如果可能的话,Wendy 只能做 2 站,所以最少需要两次换车。 (参见下面的预期结果)
我认为使用列表是最好的方法,但不确定 4 维数组是否也是一种选择。
到目前为止我的进展:
列表应该是这样的
Wendy = ['station4','station3','station4','station3']
Mike = ['station1','station2','station5','station6']
...
Tom = ['station2','station4','station6','station2']
我知道这很棘手且困难,但我不知道如何继续
这是可能有帮助的部分答案。它会生成一个
dict
,其中每个条目都是一个名称,并且有一个列表。
import pandas as pd
import numpy as np
#Data to DataFrame
data = {'Name': ['Tom', 'Mike', 'Carl', 'Juli', 'Tina', 'Wendy'],
'station1': [0, 1, 1, 1, 0, 0],
'station2': [1, 1, 1, 1, 1, 0],
'station3': [1, 1, 1, 1, 1, 1],
'station4': [1, 1, 1, 1, 1, 1],
'station5': [0, 1, 0, 0, 1, 0],
'station6': [1, 1, 0, 1, 1, 0]}
df = pd.DataFrame(data)
#Replace '1' with "station<number>"
df_stations = df.apply(lambda col: np.where(col==1, col.name, 0) if col.name != 'Name' else col, axis=0)
#Create a dictionary like {'Tom': [..., 'station2', ...],
# 'Mike': ...
# }
lists = df_stations.values.tolist()
#Remove '0' from each list
lists2 = []
for list in lists:
lists2.append([item for item in list if item != '0'])
lists = lists2
names_dict = {}
for list in lists:
names_dict[list[0]] = list[1:]
names_dict