如何组合两个具有相同格式但不同长度索引的pandas数据帧

时间:2018-03-12 22:10:36

标签: python python-2.7 pandas dataframe

我有多个数据帧。每个数据帧都有时间索引,它们都是相同的格式(日期时间)。问题是某些数据框架从2000年到2004年,而其他数据框架从2001年到2004年,依此类推。我不知道哪个数据帧的时间最长。例如,

df1
             companyA
2000-01-01   10    
2000-02-01   13
2000-03-01   21
2000-04-01   11
2000-05-01   9
2000-06-01   18
      .
      .
      .
2017-09-01   3
2017-10-01   14
2017-11-01   20
2017-12-01   5

df2
             companyB
2004-01-01   19    
2004-02-01   32
2004-03-01   17
2004-04-01   42
2004-05-01   29
2004-06-01   31
      .
      .
      .
2017-09-01   43
2017-10-01   54
2017-11-01   30
2017-12-01   45

我想把它变成

df1
             companyA    companyB    companyC...
2000-01-01   10          0           0
2000-02-01   13          0           0
2000-03-01   21          0           0
2000-04-01   11          0           0
2000-05-01   9           0           0
2000-06-01   18          0           0
      .
      .
      .
2004-01-01   19          19           0
2004-02-01   12          32           0
2004-03-01   17          17           0
2004-04-01   12          42           0
2004-05-01   19          29           0
2004-06-01   11          31           0
      .
      .
      .
2017-09-01   3           43           15
2017-10-01   14          34           24
2017-11-01   20          50           14
2017-12-01   5           45           21

我已经尝试了

df = pd.concat([df1, df2, df3, .....], axis = 1)

但它只是堆叠而忽略了索引。 我也尝试过合并,但它也没有用。

编辑:

pd.merge(df1,df2,left_index=True,right_index=True,how='outer').fillna(0)

这完全是我想要做的,但是,有没有办法合并两个以上的数据帧?如果我有100家公司,我不想重复这100次。

3 个答案:

答案 0 :(得分:0)

这就是你想要的吗?

pd.concat([df1,df2]).fillna(0)

或:

pd.merge(df1,df2,left_index=True,right_index=True,how='outer').fillna(0)
Out[9]: 
            companyA  companyB
2000-01-01      10.0       0.0
2000-02-01      13.0       0.0
2000-03-01      21.0       0.0
2000-04-01      11.0       0.0
2000-05-01       9.0       0.0
2000-06-01      18.0       0.0
2004-01-01       0.0      19.0
2004-02-01       0.0      32.0
2004-03-01       0.0      17.0
2004-04-01       0.0      42.0
2004-05-01       0.0      29.0
2004-06-01       0.0      31.0
2017-09-01       3.0      43.0
2017-10-01      14.0      54.0
2017-11-01      20.0      30.0
2017-12-01       5.0      45.0

答案 1 :(得分:0)

您也可以将.join用于此目的

df1.join(df2, how='outer).join(df3, how='outer')

.join(dataFrame,how =' outer')

将加入数据帧,使索引是所有使用的数据帧的索引的并集。

答案 2 :(得分:0)

我想合并很多DataFrame时遇到相同的问题。递归函数为我解决了它。

from random import randint
import numpy as np
import pandas as pd

def rand_dataframe(x):
    rnd = randint(2,10)
    return pd.DataFrame(np.random.rand(rnd), index = range(rnd))


def rec_merge(data, merged = None):
    if len(data) == 0:
        return merged
    if type(merged) == type(None):
        return rec_merge(data[1:], data[0])
    return rec_merge(data[1:], pd.merge(merged, data[0], left_index=True, right_index=True, how='outer').fillna(0))


dummy = map(rand_dataframe, range(randint(2,10)))
rec_merge(dummy)