我有 3 個熊貓資料框。我想將每次迭代中的每一行附加到現有資料幀。
示例如下所示:
DF1 =
col1 col2 col3
a a a
d d d
g g g
DF2=
col1 col2 col3
b b b
e e e
h h h
DF3=
col1 col2 col3
c b b
f f f
i i i
clean_DF =
col1 col2 col3
a a a
b b b
c c c
d d d
e e e
f f f
g g g
h h h
i i i
虛擬代碼:
for i,j in df1.itterows():
for a,b in df2.itterows():
for c,d in df2.itterrows():
clean_df.append(i,j,a,b,c,d)
請有人能指出我正確的方向嗎?
uj5u.com熱心網友回復:
連接它們,使用keys引數將索引與每個原始資料幀中的行相關聯,然后交換索引級別并按此索引對資料幀進行排序。
df1 = pd.DataFrame([["a", "a", "a"], ["d", "d", "d"], ["g", "g", "g"]], columns=["col1", "col2", "col3"])
df2 = pd.DataFrame([["b", "b", "b"], ["e", "e", "e"], ["h", "h", "h"]], columns=["col1", "col2", "col3"])
df3 = pd.DataFrame([["c", "c", "c"], ["f", "f", "f"], ["i", "i", "i"]], columns=["col1", "col2", "col3"])
clean_df = pd.concat([df1, df2, df3], keys=range(3)).swaplevel().sort_index()
這假設每個資料幀當前都有一個索引并按該索引排序。如果您有可能未按索引排序的資料框,并且您想保留它們當前的排序順序,那么您可以在連接它們之前重置它們的索引。
dfs = [df.reset_index() for df in [df1, df2, df3]]
clean_df = pd.concat(dfs, keys=range(len(dfs))).swaplevel().sort_index()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408650.html
標籤:
