减去索引 - TypeError:无法使用此索引类型执行__sub__:<class'pandas.core.indexes.base.index'=“”>

时间:2018-05-04 11:43:18

标签: python pandas

我有两个巨大的数据帧 我正在合并它们,但我不想重复列,所以我通过减去它来选择列:

cols_to_use=df_fin.columns-df_peers.columns.difference(['cnpj'])
df=df_peers.merge(df_fin[cols_to_use],on='cnpj',how='left')

我收到此错误(在第一行):

TypeError: cannot perform __sub__ with this index type: <class 'pandas.core.indexes.base.Index'>

df_fin.columns:
Index(['cnpj', 'ano', 'id', 'unit', 'period', 'Ativo Circulante',
   'Ativo Nao-Circulante', 'Ativo Total', 'Custos', 'Depreciacao',
   'Despesas Financeiras', 'EBITDA', 'Lucro Antes do Resultado Financeiro',
   'Lucro Antes dos Impostos', 'Lucro Bruto', 'Lucro Liquido',
   'Passivo Circulante', 'Passivo Nao-Circulante', 'Passivo Total',
   'Patrimonio Liquido', 'Receita Liquida', 'Receitas Financeiras',
   'Crescimento', 'MgLucro', 'Custo/Receita', 'MgBruta', 'MgEBITDA',
   'Passivo/EBITDA', 'LiqCorrente', 'LiqGeral', 'Resultado Financeiro',
   'RFinanceiro/Receita', 'ROA', 'ROE', 'Razao_social', 'Nome_Fantasia',
   'Estado', 'Cidade', 'CNAE', '#CNAE', 'Capital_Social', 'Data_fundacao',
   'CEP', 'Bairro', 'Rua', 'Numero', 'Complemento_endereco',
   'Natureza_Juridica', 'Telefone', 'email', 'last_revenue_normalized',
   'last_revenue_year', 'situacao_cadastral', 'situacao_especial',
   'Unnamed: 0'],
  dtype='object')

df_peers.columns:
Index(['Unnamed: 0', 'cnpj', 'Razao_social', 'Nome_Fantasia', 'Estado',
   'Cidade', 'CNAE', '#CNAE', 'Capital_Social', 'Data_fundacao',
   ...
   'Custo/Receita_t44_Peers_CNAEbisavo_estado_porte',
   'MgBruta_t44_Peers_CNAEbisavo_estado_porte',
   'Crescimento_t44_Peers_CNAEbisavo_estado_porte',
   'cnpj_t44_Peers_CNAEbisavo_estado_porte',
   'MgEBITDA_t44_Peers_CNAEbisavo_estado_porte',
   'Passivo/EBITDA_t44_Peers_CNAEbisavo_estado_porte',
   'ROE_t44_Peers_CNAEbisavo_estado_porte',
   'RFinanceiro/Receita_t44_Peers_CNAEbisavo_estado_porte',
   'ROA_t44_Peers_CNAEbisavo_estado_porte',
   'MgLucro_t44_Peers_CNAEbisavo_estado_porte'],
  dtype='object', length=250)

有人知道这可能意味着什么,或者是另一种做同样事情的方法吗?

1 个答案:

答案 0 :(得分:2)

要查找索引的差异,有difference(您已经在使用)。您无法通过columns减去- - 错误告诉您lass不支持此操作。

要查找df_fin中不在df_peers中的所有列,您可以使用

cols_to_use=df_fin.columns.difference(df_peers.columns)

如果您想要从此cnpj中删除,也可以使用

cols_to_use=df_fin.columns.difference(df_peers.columns).difference(['cnpj'])

修改

如果要获得没有重复的列的联合(按顺序),可以使用

from collections import OrderedDict

list(OrderedDict.fromkeys(list(df_fin.columns) + list(df_peers.columns)))