将pd.dataframe中的列的一部分替换为具有不同长度的数组

时间:2019-04-19 11:31:50

标签: python pandas dataframe

我想创建一个具有多个长度不同的列的数据框,因为我认为使用pd.dataframe是不可能的。我首先创建一个仅包含零的数据框,现在我想用一个数组替换每一列,我以前存储过(长度不同)。我已经尝试过dataframe.replace和dataframe.update,但无法获得此结果。

enter image description here

数组的类型和形状为: enter image description here

2 个答案:

答案 0 :(得分:2)

您必须从索引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

答案 1 :(得分:1)

您可以通过创建新列并定义长度和位置,将数组添加到数据框:

random_array = range(0,12)
df['new_column'][0:12] = random_array