、ajcr's answerを参照してくださいです。
パンダバージョンの場合
< 0.19.0:
:あなたは将来を埋めるためにはNaNが所望の値と値、およびそれらの値と、その後
update
df1
ffill
を使用し、
concat
で、2つのデータフレームを組み合わせることができ
import pandas as pd
df2 = pd.DataFrame({'value':[0.612303,0.482605,0.604132]}, index=pd.DatetimeIndex(['2015-10-06 09:00:00', '2015-10-06 10:00:00', '2015-10-06 11:00:00']))
df1 = pd.DataFrame({'value':[0.412303, 0.112303, 0., 0.000005, 0.133132]}, index=pd.DatetimeIndex(['2015-10-06 09:05:00', '2015-10-06 09:08:00', '2015-10-06 09:28:00', '2015-10-06 10:15:00', '2015-10-06 11:00:00']))
df1.update(pd.concat([df1, df2], axis=1).ffill().iloc[:, 1])
print(df1)
利回り
value
2015-10-06 09:05:00 0.612303
2015-10-06 09:08:00 0.612303
2015-10-06 09:28:00 0.612303
2015-10-06 10:15:00 0.482605
2015-10-06 11:00:00 0.604132
が
df2.index
がソート順にすでにあることを前提としていることを
import pandas as pd
df2 = pd.DataFrame({'value':[0.612303,0.482605,0.604132]}, index=pd.DatetimeIndex(['2015-10-06 09:00:00', '2015-10-06 10:00:00', '2015-10-06 11:00:00']))
df1 = pd.DataFrame({'value':[0.412303, 0.112303, 0., 0.000005, 0.133132]}, index=pd.DatetimeIndex(['2015-10-06 09:05:00', '2015-10-06 09:08:00', '2015-10-06 09:28:00', '2015-10-06 10:15:00', '2015-10-06 11:00:00']))
df1['value'] = df2.iloc[df2.index.searchsorted(df1.index, side='right')-1].values
print(df1)
利回り
value
2015-10-06 09:05:00 0.612303
2015-10-06 09:08:00 0.612303
2015-10-06 09:28:00 0.612303
2015-10-06 10:15:00 0.482605
2015-10-06 11:00:00 0.604132
注:
また、あなたはdf1.index
がdf2.index
に収まる場所を示す指標値を見つけるためにsearchsorted
を使用することができます。そうでない場合は、最初にdf2 = df2.sort_index()
を使用してください。 DatatimeIndexでソート ために、df1.index
及び/又はdf2.index
がソート順でない場合でも、データフレームを返しpd.concat
対照的に、
。したがって、最初のメソッドはsort_index
を呼び出す必要はありません。
searchsorted
の方が高速です。たとえば、この設定では、
import numpy as np
import pandas as pd
N = 1000
df1 = pd.DataFrame(np.random.random(N), index=pd.date_range('2000-1-1', periods=N, freq='14T'))
df2 = pd.DataFrame(np.random.random(int(N/60*14)), index=pd.date_range('2000-1-1', periods=int(N/60*14), freq='1H'))
df3, df4 = df1.copy(), df1.copy()
df3.update(pd.concat([df3, df2], axis=1).ffill().iloc[:, 1])
df4[0] = df2.iloc[df2.index.searchsorted(df4.index, side='right')-1].values
assert df3.equals(df4)
searchsorted
は〜2です。8倍高速化:
In [88]: %timeit df3.update(pd.concat([df3, df2], axis=1).ffill().iloc[:, 1])
100 loops, best of 3: 2.13 ms per loop
In [89]: %timeit df4[0] = df2.iloc[df2.index.searchsorted(df4.index, side='right')-1].values
1000 loops, best of 3: 744 µs per loop
In [90]: len(df1), len(df2)
Out[90]: (1000, 233)
['merge_asof'](http://pandas.pydata.org/pandas-docs/stable/merging.html#merging-asof)がこの目的のために存在します。 –
@ajcr私の問題を解決しました。ありがとう、私が受け入れる答えを書いてみたいですか? –
以下の 'merge_asof'を使って答えを追加しました。詳細を知りたい場合はお知らせください。 –