【问题标题】:Fill column with last known value after pandas df.stack在 pandas df.stack 之后用最后一个已知值填充列
【发布时间】:2021-04-20 03:09:33
【问题描述】:

我想弄清楚在堆叠数据框后如何填充日期之间的空白。我希望每个股票代码都有各自的日期,而不是每个日期只反映一次。感谢您的帮助。

import pandas as pd
from yahoofinancials import YahooFinancials
positions_held = ['MSFT', 'AAPL', 'AMZN','SPOT']

yahoo_financials = YahooFinancials(positions_held)

data = yahoo_financials.get_historical_price_data(start_date='2020-12-28',
                                                  end_date='2021-12-31',
                                                  time_interval='daily')

df = pd.DataFrame({
    a: {x['formatted_date']: x['adjclose'] for x in data[a]['prices']} for a in positions_held
})

df = df.stack(dropna=True)

df.fillna(method='ffill', inplace=True)

print(df)

【问题讨论】:

    标签: python pandas dataframe stack


    【解决方案1】:

    这将为您提供最灵活的数据框

    df = df.unstack(level=-1)
    

    会给你

                MSFT        AAPL        AMZN        SPOT
    2020-12-28  224.960007  136.690002  3283.959961 317.290009
    2020-12-29  224.149994  134.869995  3322.000000 318.429993
    2020-12-30  221.679993  133.720001  3285.850098 319.350006
    

    【讨论】:

    • 谢谢,但我特别希望数据垂直排列,这就是为什么我首先堆叠它
    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多