为了账号安全,请及时绑定邮箱和手机立即绑定

如何将一个 numpy 数组合并到多个数据帧上

如何将一个 numpy 数组合并到多个数据帧上

蝴蝶不菲 2022-11-18 20:42:16
我有一堆数据框。它们都有相同的列,但行数不同。它们看起来像这样:df_1    00  11  02  03  14  15  0df_2   00  11  02  03  1df_3   00  11  02  03  14  1我把它们都存储在一个列表中。然后,我有一个 numpy 数组,其中每个项目映射到每个单独的 df 中的一行。numpy 数组如下所示:[3 1 1 2 4 0 6 7 2 1 3 2 5 5 5]如果我要 pd.concat 我的数据帧列表,那么我可以将 np 数组合并到串联的 df 上。但是,我想保留单独的 df 结构,因此它应该如下所示:   0  10  1  31  0  12  0  13  1  24  1  45  0  0   0  10  1  61  0  72  0  23  1  1   0  10  1  31  0  22  0  5 3  1  54  1  5
查看完整描述

1 回答

?
米脂

TA贡献1836条经验 获得超3个赞

考虑给定的数据帧和数组,


df1 = pd.DataFrame([1,0,0,1,1,0])

df2 = pd.DataFrame([1,0,0,1])

df3 = pd.DataFrame([1,0,0,1,1])


arr = np.array([3, 1, 1, 2, 4, 0, 6, 7, 2, 1, 3, 2, 5, 5, 5])

您可以根据给定的数据帧numpy.split将 an 拆分array为多个子数组。然后,您可以将这些数组作为列附加到它们各自的数据帧中。


利用:


dfs = [df1, df2, df3]


def get_indices(dfs):

    """

    Returns the split indices inside the array.

    """

    indices = [0]

    for df in dfs:

        indices.append(len(df) + indices[-1])

    return indices[1:-1]


# split the given arr into multiple sections.

sections = np.split(arr, get_indices(dfs))

for df, s in zip(dfs, sections):

    df[1] = s # append the section of array to dataframe

    print(df)

结果:


# df1

   0  1

0  1  3

1  0  1

2  0  1

3  1  2

4  1  4

5  0  0


#df2

   0  1

0  1  6

1  0  7

2  0  2

3  1  1


# df3

   0  1

0  1  3

1  0  2

2  0  5

3  1  5

4  1  5


查看完整回答
反对 回复 2022-11-18
  • 1 回答
  • 0 关注
  • 70 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信