Pandas 基于特定条件用另一个数据帧中的数据填充一个数据帧

Pandas 基于特定条件用另一个数据帧中的数据填充一个数据帧,pandas,python-2.7,dataframe,for-loop,if-statement,Pandas,Python 2.7,Dataframe,For Loop,If Statement,我有一个名为“optns”的熊猫数据框,其中包含有关标准普尔500指数期权的信息,有3列:“日期”、“最佳报价”、“货币行情”。我创建了一个新的数据框“price”,它有8列,代表“Money Ticker”的不同值。我想用相应日期的“最佳报价”值填充此数据框。我写了一个代码,但它远远没有效率,甚至可能是错误的: for j in range(0,price.shape[0]): for i in range(0,optns.shape[0]): if (price.lo

我有一个名为“optns”的熊猫数据框,其中包含有关标准普尔500指数期权的信息,有3列:“日期”、“最佳报价”、“货币行情”。我创建了一个新的数据框“price”,它有8列,代表“Money Ticker”的不同值。我想用相应日期的“最佳报价”值填充此数据框。我写了一个代码,但它远远没有效率,甚至可能是错误的:

for j in range(0,price.shape[0]):
    for i in range(0,optns.shape[0]):
        if (price.loc[j,'Date']==optns.loc[i,'Date']) and (optns.loc[i,'Money Ticker']== 'Call OTM 10%'):
            price.loc[j,'Call OTM 10%']=optns.loc[i,'best_offer']
        if (price.loc[j,'Date']==optns.loc[i,'Date']) and (optns.loc[i,'Money Ticker']== 'Call OTM 7%'):
            price.loc[j,'Call OTM 7%']=optns.loc[i,'best_offer']
        if (price.loc[j,'Date']==optns.loc[i,'Date']) and (optns.loc[i,'Money Ticker']== 'Call OTM 5%'):
            price.loc[j,'Call OTM 5%']=optns.loc[i,'best_offer']
        if (price.loc[j,'Date']==optns.loc[i,'Date']) and (optns.loc[i,'Money Ticker']== 'Call ATM'):
            price.loc[j,'Call ATM']=optns.loc[i,'best_offer']
        if (price.loc[j,'Date']==optns.loc[i,'Date']) and (optns.loc[i,'Money Ticker']== 'Put ATM'):
            price.loc[j,'ATM']=optns.loc[i,'best_offer']
        if (price.loc[j,'Date']==optns.loc[i,'Date']) and (optns.loc[i,'Money Ticker']== 'Put OTM 5%'):
            price.loc[j,'Put OTM 5%']=optns.loc[i,'best_offer']
        if (price.loc[j,'Date']==optns.loc[i,'Date']) and (optns.loc[i,'Money Ticker']== 'Put OTM 7%'):
            price.loc[j,'Put OTM 7%']=optns.loc[i,'best_offer']
        if (price.loc[j,'Date']==optns.loc[i,'Date']) and (optns.loc[i,'Money Ticker']== 'Put OTM 10%'):
            price.loc[j,'Put OTM 10%']=optns.loc[i,'best_offer']

我该怎么做?谢谢大家!

我相信你要找的是。 我不确定我是否完全理解了您的数据帧,但如果我理解了,这将解决您的问题:

pd.pivot_table(optns, columns="Money Ticker", values="Best Offer", index="Date")
您可以查看链接文档以了解更多信息