我想创建一个包含多个长度不同的列的数据框,因为我认为这对于 pd.dataframe 是不可能的我之前存储过(不同长度)。我已经尝试过 dataframe.replace 和 dataframe.update 但我无法得到这个结果。
最佳答案
您必须从索引 1
插入数组。为此你可以做到,
df['dobs'][1:] = dobs
所有数组都类似。
考虑一个示例数据框,
df = pd.DataFrame()
df['dobs'] = [0.] * 45
df['dpred_0'] = [0.] * 45
df['dpred'] = [0.] * 45
df['mrec'] = [0.] * 45
现在,一些你在问题中提到的形状的占位符数组,
dobs = np.array([x for x in range(1, 45)])
dpred_0 = np.array([x for x in range(1, 45)])
dpred = np.array([x for x in range(1, 45)])
mrec = np.array([x for x in range(1, 46)])
让我们检查形状,
print(dobs.shape, dpred_0.shape, dpred.shape, mrec.shape, df.shape) # ((44,), (44,), (44,), (45,), (45, 4))
要将索引 1
中的列替换为更短的数组,您可以这样做,
df['dobs'][1:] = dobs
df['dpred_0'][1:] = dpred_0
df['dpred'][1:] = dpred
df['mrec'] = mrec # mrec is of shape (45, ) so no need to start from index 1
dobs dpred_0 dpred mrec
0 0.0 0.0 0.0 1
1 1.0 1.0 1.0 2
2 2.0 2.0 2.0 3
3 3.0 3.0 3.0 4
4 4.0 4.0 4.0 5
关于python - 将 pd.dataframe 中的部分列替换为具有不同长度的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55761175/