3

I have a DataFrame df1 (index as a datetime) and df2 with many columns,different length index.
I need to combine df1with df2, replacing index in df2. As a result presented df3.

df1
                      T1
2011-09-01 00:00:00   10
2011-09-01 00:10:00   20
2011-09-01 00:20:00   30  
2011-09-01 00:30:00   40

df2
    T2   T3        
0   1.1  2.0 
1   1.2  3.0
2   1.3  4.0

df3
                      T1   T2  T3
2011-09-01 00:00:00   10  1.1  2.0
2011-09-01 00:10:00   20  1.2  3.0
2011-09-01 00:20:00   30  1.3  4.0
2011-09-01 00:30:00   40  Nan  Nan

I wanted to try concat, join, merge, append but those doesn't seem to be appropriate.
Using set_index resulted in having an error: length mismatch.

I end up trying this:

  df3=pd.DataFrame(df2,index=df1.index,copy=True)

I got the desired index, and columns from df2 but they were empty.

4

2 に答える 2

5

これを行う1つの方法は次のとおりです。

In [32]: from pandas import DataFrame, date_range, concat

In [33]: from numpy.random import randn

In [34]: df = DataFrame(randn(5, 1), index=date_range('20010101', periods=5), columns=['A'])

In [35]: df2 = DataFrame(randn(3, 2), columns=list('BC'))

In [36]: concat([df, df2.set_index(df.index[:len(df2)])], axis=1)
Out[36]:
                A      B      C
2001-01-01 -0.043  0.759 -0.125
2001-01-02 -1.377  0.895  0.629
2001-01-03  0.263 -0.007 -0.515
2001-01-04  1.546    NaN    NaN
2001-01-05 -0.657    NaN    NaN

DataFrame.join()少し短いコードでこれを行うこともできます。

In [7]: df.join(df2.set_index(df.index[:len(df2)]))
Out[7]:
                A      B      C
2001-01-01 -0.607 -0.038  0.593
2001-01-02  0.573  0.399 -0.627
2001-01-03  0.319  0.312 -0.152
2001-01-04 -1.671    NaN    NaN
2001-01-05 -1.589    NaN    NaN
于 2013-08-22T21:57:56.187 に答える