我是python熊貓的新手。只是一個簡單而快速的問題。假設我有兩列,分別是「周」和「機」:平鋪數據來創建一個熊貓數據框
weeks = [1,3,5]
machine = [M1, M1, M2, M2]
我的計劃是把這些名單的數據幀,但我得到「ValueError異常:數組必須是相同的長度」。我正在看以下輸出:
final_weeks = [1,2,3,4,5,1,2,3,4,5]
final_machine = [M1, M1, M1, M1, M1, M2, M2, M2, M2, M2]
tempDict = {'weeks': final_weeks, 'machine': final_machine}
我得到這兩個列表,但不是數據框。爲什麼我得到valueError?下面是我做的,到目前爲止:
maxWeek = df["weeks"].max()
uniqueMachine = set(df.machine)
unionWeeklist = [item for item in range(1, maxWeek+1)]
# Output = [1, 2, 3, 4, 5]
final_weeks = unionWeekList * len(uniqueMachine)
# [1,2,3,4,5,1,2,3,4,5]
machines = [[item]* maxWeek for item in uniqueMachine]
# Output: [[M1,M1,M1,M1,M1], [M2,M2,M2,M2,M2]]
final_machines = list(itertools.chain.from_iterable(machines))
# Flattened list = [M1,M1,M1,M1,M1,M2,M2,M2,M2,M2]
tmpDict = {'week': final_weeks, 'machine': final_machines}
# new dataframe
newdf = pd.DataFrame.from_records(tmpDict)
# ValueError: arrays must all be same length
能否打印'LEN(final_weeks)'和'LEN(final_machines) ' – Wen
其記錄數量相同,沒有問題。 – SalN85
好的,我更新了。 – Wen