我有一个要迭代添加行的数据框。列是“时间”的整数,(x,y)坐标和二分状态。为了本示例的目的,而不是完整的迭代,我将演示向数据帧添加一行而不是增加一行的问题。问题似乎是,当我将新行连接到现有数据帧时,它将我的元组(5,0)分解为两个整数值,因此有两行试图添加而不是仅添加一行,并且所以我得到一个错误:“ ValueError:数组必须都具有相同的长度”。我怎样才能解决这个问题?
import pandas as pd
import numpy as np
# set up coordinates for a 10x10 grid
m=10
n=10
coordinates = []
for x in range(m):
for y in range(n):
coordinates.append((x,y))
# set the state of each point to "ON" or "OFF"
states = np.random.choice(["ON","OFF"],size=len(coordinates), replace=True, p=[0.2, 0.8])
# collate the above into a dataframe
df = pd.DataFrame({"time": np.zeros(len(coordinates)), "individual": coordinates, "state": states})
# pick a random point
point = coordinates[50]
# add row for time+1 to the data frame.
df = pd.concat([df, pd.DataFrame({"time": 1, "individual": point, "state": np.random.choice(["ON","OFF"],1, replace=True, p=[0.2, 0.8])})])
您只需要在括号周围添加括号,coordinates[50]
以避免拆分元组:
point = [coordinates[50]]
(结束)输出:
95 0.0 (9, 5) ON
96 0.0 (9, 6) OFF
97 0.0 (9, 7) ON
98 0.0 (9, 8) OFF
99 0.0 (9, 9) ON
0 1.0 (5, 0) OFF
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句