首页 > 解决方案 > [Index([(...column names...)], dtype='object', name='Sample Name')] 中没有一个在 [index]

问题描述

我有一个看起来像的数据框 df1

Sample Name    col1    col2   col3  
     a           1       2      3
     b           4       5      6
     c           7       8      9

从excel中读取然后转置它并将转置的df存储在df1T中。我将索引设置为样本名称,因此列是样本名称

dfT=df.set_index('Sample Name').T

      a    b   c
col1  1    4   7
col2  2    5   8
col3  3    6   9

我有另一个包含 a 和 b 列的数据框 df2。

      a    b
row1  x    y

我想将一行从 df1T(例如:col1,我们可以命名为 col1)添加到 df2,只取 df2 中的列(a 和 b)

      a    b
row1  x    y
col1  1    4

所以我写了

df2.loc["col1"]=df1T.loc["col1",[df2.columns]]

但我得到错误没有索引(列名)......即使在 [index] 中,即使 df1t.columns 和 df2.columns 显示列名匹配并且是正确的。

标签: pythonexcelpython-3.xpandas

解决方案


您可以使用:

df2.loc["col1"]=df.loc["col1",df2.columns.tolist()]

输出:

        a   b
row1    x   y
col1    1   4

你的错误是什么?

[df2.columns] 

它是一个包含 的列表df.columns,但它不会创建包含列索引的列表。

type(df2.columns)

它返回:

pandas.core.indexes.base.Index

推荐阅读