Pandas基于索引/列组合合并DataFrames

时间:2016-07-19 15:09:00

标签: python pandas dataframe

我想要DataFrames我有两个merge。我读过有关merging on multiple columnspreserving the index when merging的文章。我的问题需要适应两者,而我很难找到最佳方法。

第一个DataFrame看起来像这样

enter image description here

,第二个看起来像这个

enter image description here

我想根据Date ID合并这些内容。在第一个DataFrame中,Date是索引,ID是列;在第二个DataFrame中,DateID都是MultiIndex的一部分。

基本上,因此我想要一个看起来像DataFrame 2的DataFrame,并为DataFrame 1中的Events增加一列。

1 个答案:

答案 0 :(得分:1)

我建议重新设置索引(<?php namespace My\Bundle\Command; use My\AccommodationBundle\Entity\Visit; use My\NewAccommodationBundleV2\Entity\Visit as Visit2; use My\OtherBundle\Entity\Person; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class VisitConvertToNewFormatCommand extends ContainerAwareCommand { private $em; protected function configure() { $this ->setName('accommodation:visit:convert') ->setDescription("Converting old structure to new structure'") ; } protected function getTimeStamp() { $currentTime = new \DateTime('now'); return '['.$currentTime->format('Y-m-d H:i:s').'] '; } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln($this->getTimeStamp().$this->getDescription()); $this->em = $this->getContainer()->get('doctrine')->getManager(); $visits = $this->em->getRepository('MyOldAccommodationBundle:Visit')->findAll(); foreach ($visits as $visit) { $visit2 = new Visit2(); $visit2->setArrivalDate($visit->getArrivalDate()); $visit2->setArrivalStatus($visit->getArrivalStatus()); $visit2->setArrivalTime($visit->getArrivalTime()); $visit2->setBookingType($visit->getBookingType()); $visit2->setCountry($visit->getCountry()); // <---- ... $this->em->persist($visit2); $user = $visit->getUser(); if ($user != null) { $person = new Person(); ... $person->setFirstName(trim(ucfirst(strtolower($user->getFirstName())))); $person->setLastName(trim(ucfirst(strtolower($user->getLastName())))); $person->setEmail(preg_replace('/\s+/', '', $user->getEmail())); ... $this->em->persist($person); } } } } )然后合并DataFrame,如您所读。然后,您可以设置索引(reset_index)以重现所需的MultiIndex。