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

我有一堆数据框。它们都有相同的列,但行数不同。它们看起来像这样:


df_1 

   0

0  1

1  0

2  0

3  1

4  1

5  0


df_2

   0

0  1

1  0

2  0

3  1


df_3

   0

0  1

1  0

2  0

3  1

4  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  1

0  1  3

1  0  1

2  0  1

3  1  2

4  1  4

5  0  0


   0  1

0  1  6

1  0  7

2  0  2

3  1  1


   0  1

0  1  3

1  0  2

2  0  5 

3  1  5

4  1  5


蝴蝶不菲
浏览 72回答 1
1回答

米脂

考虑给定的数据帧和数组,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  10  1  31  0  12  0  13  1  24  1  45  0  0#df2   0  10  1  61  0  72  0  23  1  1# df3   0  10  1  31  0  22  0  53  1  54  1  5
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python