繁体   English   中英

如何基于其他数据框创建和填充 pandas 行?

[英]How to create and populate pandas row based on other dataframes?

我根据某些条件从原始df创建了df2df3 现在,我想 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

这是一个带有maploc的命题:

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

看看这个也许它可以帮助你。

# Create a new row for Subtype
subtype = []
for column in df.columns:
    if column in df2.columns:
        subtype.append('Table2')
    elif column in df3.columns:
        subtype.append('Table3')
df.loc['Subtype'] = subtype

输出

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])

更改按以下顺序进行:

  1. 相应地创建Table2Table3的列表,从df1.columns[1:]开始跳过第一个未命名的列。
  2. 将第一列设置为行的索引,因为我们不想看到编号的行。
  3. 从我们之前构建的列表中创建一个新的 dataframe(第 1 步)
  4. 连接两个数据帧

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM