在沿列求和时如何忽略熊猫中丢失的键

时间:2019-10-24 17:09:55

标签: python pandas

我有一个pandas数据框,其中包含单词嵌入。单词是列名。为了获得最终的句子嵌入,我这样做:

st = ['some','random','text']
a = df[st].sum(axis=1)

当所有术语都出现在数据框中时,这很好用。但是,当数据帧中不存在该列时,它将引发密钥错误。目前,我正在为每个学期循环学习,除了尝试。我想避免循环,并在一行中执行该操作。熊猫提供相同的选项吗?

2 个答案:

答案 0 :(得分:1)

使用intersection

df[df.columns.intersection(st)].sum(axis=1)

这只会对列在df中的列求和

答案 1 :(得分:0)

您可以将任务替换为:

@InjectMocks
@Spy
private ContractServiceImpl service;

@Mock
ContractRepository contractRepository;

@Mock
OasysContractRepository oasysContractRepository;

@Mock
ContractServiceManager serviceManager;


public static final String contractNumber = "3900006835";

@Test
public void getListOfContractBy_hcp_success() {
    List<OasysContract> oasysContractList = new ArrayList<>();
    oasysContractList.isEmpty();

    List<Contract> contractList = new ArrayList<>();
    contractList.add(BuildUtil.buildContract());

    //mock
    Mockito.doReturn(oasysContractList).when(oasysContractRepository).findByContractNumber(contractNumber);
    Mockito.doReturn(BuildUtil.buildContractList()).when(contractRepository).findContractsByContractNumber(contractNumber);
    Mockito.doReturn(contractList).when(serviceManager).checkPgwContract(contractList);
    Mockito.doReturn(BuildUtil.buildContract()).when(contractRepository).findContractByExpiredDate(contractNumber);
    Mockito.doReturn("N").when(contractRepository).getFullyPaid(contractNumber);


    //test
    List<Contract> contracts = service.getListOfContractBy(contractNumber);

    System.out.println(contracts);

    assert(!contracts.isEmpty());
}

消除所有不存在的单词。