我有兩個如下所示的資料框:
df1 = pd.DataFrame(
{
"A_price": [10, 12],
"B_price": [20, 21],
},
index = ['01-01-2020', '01-02-2021']
)
df1:
A_price B_price
01-01-2020 10 20
01-02-2021 12 21
df2 = pd.DataFrame(
{
"A_weight": [0.1, 0.12],
"B_weight": [0.2, 0.21],
},
index = ['01-01-2020', '01-02-2021']
)
df2:
A_weight B_weight
01-01-2020 0.1 0.2
01-02-2021 0.12 0.21
如何在相同的索引上連接兩個資料框,然后在層次結構中放置列?即我想要以下內容:
df:
A B
price weight price weight
01-01-2020 10 0.1 20 0.2
01-02-2021 12 0.12 21 0.21
uj5u.com熱心網友回復:
使用join(或merge)并分解您的列名。
# out = pd.merge(df1, df2, left_index=True, right_index=True)
out = out.join(df2)
out.columns = out.columns.str.split('_', expand=True)
out = out.sort_index(axis=1)
print(out)
# Output:
A B
price weight price weight
01-01-2020 10 0.10 20 0.20
01-02-2021 12 0.12 21 0.21
uj5u.com熱心網友回復:
簡單地的concat水平地pd.concat與axis=1,并且通過拆分柱_用.columns.str.split(其與expand=True回傳一個MultiIndex):
new_df = pd.concat([df1, df2], axis=1)
new_df.columns = new_df.columns.str.split('_', expand=True)
輸出:
>>> new_df
A B A B
price price weight weight
01-01-2020 10 20 0.10 0.20
01-02-2021 12 21 0.12 0.21
uj5u.com熱心網友回復:
這應該有效。
pd.concat((df1.T,df2.T), keys=["A", "B"]).T
uj5u.com熱心網友回復:
您可以使用pd.concat使用keys引數與sort_index()在正確的結構得到他們。然后rename在多索引的內部級別洗掉前綴的列:
df = pd.concat([df1, df2], keys=['A','B'],axis=1).sort_index(level=1, axis=1)
df.rename(columns=lambda x: x.split('_')[1], level=1)
A B A B
price weight price weight
01-01-2020 10 0.10 20 0.20
01-02-2021 12 0.12 21 0.21
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/389442.html
