【问题标题】:Pandas: merge two dataframes with different index and missing valuesPandas:合并具有不同索引和缺失值的两个数据框
【发布时间】:2018-08-21 05:24:20
【问题描述】:

我正在尝试将两个数据框合并在一起。 df2 的样本点比 df 多。我想根据 df 的索引合并它们,以使每个时间戳中最接近时间戳的非缺失值成为值。

我的原始数据集是分类的,这就是我将列设为字符串的原因。

from datetime import datetime, timedelta
import pandas as pd
import numpy as np
import random
    ##Generate the Data
np.random.seed(12) 
date_today = datetime.now()
ndays = 5
df = pd.DataFrame({'date': [date_today + timedelta(days=x) for x in range(ndays)], 
                       'test': pd.Series(np.random.randn(ndays)),     'test2':pd.Series(np.random.randn(ndays))})
df = df.set_index('date').sort_index()
df = df.mask(np.random.random(df.shape) < .7)
print(df)

df2 = pd.DataFrame({'date': [date_today + timedelta(days=(abs(np.random.randn(1))*0.25)[0]*x) for x in range(ndays*2)], 
                       'test3': pd.Series(np.random.randn(ndays*2))})
df2 = df2.set_index('date').sort_index() 

df2 = df2.mask(np.random.random(df2.shape) < .3)
df['test']=df['test'].astype(str)
df['test2']=df['test2'].astype(str)
df2['test3']=df2['test3'].astype(str)



print(df2)
df2.reindex(df.index, method='bfill')

当前输出:

                                test3
date    
2018-03-12 22:31:52.177918  -1.6817565103951275
2018-03-13 22:31:52.177918  nan
2018-03-14 22:31:52.177918  nan
2018-03-15 22:31:52.177918  nan
2018-03-16 22:31:52.177918  nan

期望输出:

                                test3
date    
2018-03-12 22:31:52.177918  -1.6817565103951275
2018-03-13 22:31:52.177918   0.214975948415751
2018-03-14 22:31:52.177918  nan
2018-03-15 22:31:52.177918  nan
2018-03-16 22:31:52.177918  nan

提前致谢,

【问题讨论】:

    标签: python-3.x pandas indexing pandas-groupby


    【解决方案1】:

    reindex 中使用method='nearest' 参数设置

    df2.reindex(df.index, method='nearest')
    
    date                                      
    2018-03-12 20:44:02.753549   -1.6817565104
    2018-03-13 20:44:02.753549  0.214975948416
    2018-03-14 20:44:02.753549             nan
    2018-03-15 20:44:02.753549             nan
    2018-03-16 20:44:02.753549             nan
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      相关资源
      最近更新 更多