![](/img/trans.png)
[英]How to create new dataframe with pandas based on columns of other dataframes
[英]How to create and populate pandas row based on other dataframes?
我根據某些條件從原始df
創建了df2
和df3
。 現在,我想 map 通過創建一個新的行Subtype
和 label 如果列名與df2
匹配,行值作為Table2
返回到df
,而如果它與df3
的列名匹配,它將是Table3
。
df
A | 乙 | C | 丁 | 乙 | F | G | |
---|---|---|---|---|---|---|---|
第一的 | 0 | 4個 | 8個 | 12 | 16 | 20 | 24 |
第二 | 1個 | 5個 | 9 | 13 | 17 | 21 | 25 |
第三 | 2個 | 6個 | 10 | 14 | 18 | 22 | 26 |
第四 | 3個 | 7 | 11 | 15 | 19 | 23 | 27 |
第五 | 1個 | 2個 | 3個 | 北美 | 北美 | 北美 | 北美 |
df2
A | 乙 | C | |
---|---|---|---|
第一的 | 0 | 4個 | 8個 |
第二 | 1個 | 5個 | 9 |
第三 | 2個 | 6個 | 10 |
第四 | 3個 | 7 | 11 |
第五 | 1個 | 2個 | 3個 |
df3
丁 | 乙 | F | |
---|---|---|---|
第一的 | 12 | 16 | 20 |
第二 | 13 | 17 | 21 |
第三 | 14 | 18 | 22 |
第四 | 15 | 19 | 23 |
預計 output:
df
A | 乙 | C | 丁 | 乙 | F | G | |
---|---|---|---|---|---|---|---|
第一的 | 0 | 4個 | 8個 | 12 | 16 | 20 | 24 |
第二 | 1個 | 5個 | 9 | 13 | 17 | 21 | 25 |
第三 | 2個 | 6個 | 10 | 14 | 18 | 22 | 26 |
第四 | 3個 | 7 | 11 | 15 | 19 | 23 | 27 |
第五 | 1個 | 2個 | 3個 | 北美 | 北美 | 北美 | 北美 |
亞型 | 表2 | 表2 | 表2 | 表3 | 表3 | 表3 | 表3 |
d2 = {col: "Table2" for col in df2.columns}
d3 = {col: "Table3" for col in df3.columns}
df.loc["Subtype"] = list(df.columns.map({**d2, **d3}))
Output:
print(df)
A B C D E F G
First 0 4 8 12.0 16.0 20.0 24.0
Second 1 5 9 13.0 17.0 21.0 25.0
Third 2 6 10 14.0 18.0 22.0 26.0
Fourth 3 7 11 15.0 19.0 23.0 27.0
Fifth 1 2 3 NaN NaN NaN NaN
Subtype Table2 Table2 Table2 Table3 Table3 Table3 NaN
subtype = ['Table2' if col_name in df2.columns else 'Table3' for col_name in df1.columns[1:]]
df1.set_index(df1.columns[0], inplace=True)
subtype_row = pd.DataFrame([subtype], index=["Subtype"], columns=df1.columns)
df1 = pd.concat([df1, subtype_row])
更改按以下順序進行:
Table2
或Table3
的列表,從df1.columns[1:]
開始跳過第一個未命名的列。Output:
A B C D E F G
First 0 4 8 12.0 16.0 20.0 24.0
Second 1 5 9 13.0 17.0 21.0 25.0
Third 2 6 10 14.0 18.0 22.0 26.0
Fourth 3 7 11 15.0 19.0 23.0 27.0
Fifth 1 2 3 NaN NaN NaN NaN
Subtype Table2 Table2 Table2 Table3 Table3 Table3 Table3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.