我目前面臨一個問題,我無法解決。我花了 6 個小時試圖找到解決方案,但最終對我沒有任何效果,可能是因為我不使用 wright 的東西。(我正在使用 python、pandas、numpy)
想象一下,我有 2 個相同的資料幀,除了每個集群的第二個資料幀比另一個資料幀少 5 天。其中“day”和“cluster”是已排序的列名。每個集群都有不同的天數。
圖形情況是:https ://i.stack.imgur.com/w8wDk.jpg
現在我想以這樣一種方式合并/連接,即我的資料框不會根據索引合并。我希望第二個資料幀的第一行與第一個資料幀的第一行匹配。因此,它將為合并的第二個資料幀的最后 5 行引入 NA 值。
從圖形上看,情況將是:https ://i.stack.imgur.com/nFWHa.jpg
我該如何著手解決這種情況?
提前感謝您的任何幫助,我已經嘗試了很多東西,我真的在努力解決這個問題。
uj5u.com熱心網友回復:
我承認這不是最漂亮的解決方案,但至少它有效。假設較高和較短的幀分別為f1和f2,則步長為
f創建一個高度相同f1但沒有cluster列的“假”框架。- 用來自的資料逐漸填充
f取自 的相關指標。f1f2 - 將(部分填充)
f與f1
為了演示這個想法,假設兩個框架是
>>> f1
cluster day A B
0 2 0 1 2
1 2 1 3 4
2 1 2 5 6
3 1 3 7 8
>>> f2
cluster day A B
0 1 5 10 20
1 1 9 30 40
2 2 6 50 60
代碼如下(在np哪里numpy)
f = f1.drop('cluster', axis=1).copy() # the fake frame
f[:] = np.nan
f1g = f1.groupby('cluster') # Allow for a second indexing way using cluster id
f2g = f2.groupby('cluster')
clusters1 = f1g.groups.keys()
clusters2 = f2g.groups.keys()
for cluster in (clusters1 & clusters2):
idx1 = f1g.get_group(cluster).index # indices of entries of the current cluster in f1
idx2 = f2g.get_group(cluster).index # indices of entries of the current cluster in f2
m = len(idx2)
f.loc[idx1[0:m]] = f2.loc[idx2[0:m], ['day', 'A', 'B']].to_numpy() # fill the first m entries of current cluster in f with data from f2
以及將fakef和higher連接起來后的結果f1
>>> pd.concat([f1, f], axis=1)
cluster day A B day A B
0 2 0 1 2 6.0 50.0 60.0
1 2 1 3 4 NaN NaN NaN
2 1 2 5 6 5.0 10.0 20.0
3 1 3 7 8 9.0 30.0 40.0
最后說明:您可以在 for 回圈中使用 以外的方式獲取idx1and ,但我認為后者是最快的方法之一。idx2groupby
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484964.html
上一篇:R問題:我修改了兩個分類列,如何嵌入回原始資料框中?
下一篇:列groupby上的資料框直方圖
