亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將一個 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 關注
  • 101 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號