![](/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.