【问题标题】:Fill multiple rows in between pandas dataframe rows on condition根据条件在熊猫数据框行之间填充多行
【发布时间】:2020-01-19 21:31:12
【问题描述】:

我有一个如下数据集:

pd.DataFrame({'Date':['2019-01-01','2019-01-03','2019-01-01','2019-01-04','2019-01-01','2019-01-03'],'Name':['A','A','B','B','C','C'],'Open Price':[100,200,300,400,500,600],'Close Price':[200,300,400,500,600,700]})

现在我们可以看到此表中缺少几日条目。即 A 为 2019-01-02,B 为 2019-01-02、2019-01-03,C 为 2019-01-02。

我要做的是在数据框中为这些日期添加虚拟行,

收盘价列与第二天的下一个开盘价输入相同。而且我不在乎开盘价,它可以是 nan 或 0

预期输出

pd.DataFrame({'Date':['2019-01-01','2019-01-02','2019-01-03','2019-01-01','2019-01-02','2019-01-03','2019-01-04','2019-01-01','2019-01-02','2019-01-03'],'Name':['A','A','A','B','B','B','B','C','C','C'],'Open Price':[50,'nan',150,250,'nan','nan',350,450,'nan',550],'Close Price':[200,150,300,400,350,350,500,600,550,700]})

任何帮助将不胜感激!

【问题讨论】:

  • 为什么预期产量的价格会发生变化?背后的逻辑是什么?
  • 即A在2019-01-03的开盘价是150,所以我们预计A在2019-01-02的收盘价是150。
  • 我没有看到任何等于 150 的收盘价

标签: python pandas merge timestamp fillna


【解决方案1】:

对于应该如何插入价格,您的逻辑是模糊的,但为了让您开始,请考虑这一点,记住将日期转换为 datetime dtype:

df['Date'] = pd.to_datetime(df['Date'])
df = (df.groupby('Name')
        .resample('D', on='Date')
        .mean()
        .swaplevel()
        .interpolate()
)

print(df)
                 Open Price  Close Price
Date       Name                         
2019-01-01 A     100.000000   200.000000
2019-01-02 A     150.000000   250.000000   
2019-01-03 A     200.000000   300.000000
2019-01-01 B     300.000000   400.000000
2019-01-02 B     333.333333   433.333333
2019-01-03 B     366.666667   466.666667
2019-01-04 B     400.000000   500.000000  
2019-01-01 C     500.000000   600.000000
2019-01-02 C     550.000000   650.000000
2019-01-03 C     600.000000   700.000000

【讨论】:

    猜你喜欢
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    相关资源
    最近更新 更多