简体   繁体   English

将 dataframe(熊猫)中的行乘以系列

[英]Multiplying rows in a dataframe (pandas) by a series

I have this dataframe of financial data extracted with yfinance.我有这个用 yfinance 提取的财务数据 dataframe。 I am trying to multiply the daily price of each stock by a vector of positions reflecting the quantity of stocks the portfolio is holding (57 EDP.LS stocks, 2 DIS stocks, none of the others).我试图将每只股票的每日价格乘以反映投资组合持有的股票数量的头寸向量(57 只 EDP.LS 股票,2 只 DIS 股票,其他都没有)。 The code I am using is below, but all I get it a dataframe of NaNs the size of the original df + 4 rows indexed "0, 1, 2, 3" with more NaNs.我正在使用的代码如下,但我得到的只是 dataframe 的 NaN 大小,原始 df + 4 行索引为“0、1、2、3”和更多的 NaN。 What am I doing wrong?我究竟做错了什么?

from datetime import date
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime

tickers = ['EDP.LS', 'DIS', 'GILD', 'FB'] #yahoo finance tickers
firstPositions = pd.Series([57, 2, 0, 0]) #order follows tickers list
today = date.today()
df = yf.download(tickers, start='2020-02-07', end=today)['Close']
firstValues = df.mul(firstPositions, axis=0)

Thank you in advance先感谢您

If you want to multiply each column use axis=1, that should solve.如果您想将每列相乘使用axis = 1,那应该可以解决。

We should insert the ticker with the index of you mul serise我们应该插入带有你 mul serise 索引的股票代码

tickers = ['EDP.LS', 'DIS', 'GILD', 'FB'] #yahoo finance tickers
firstPositions = pd.Series([57, 2, 0, 0],index= tickers)  

Then we can do multiple然后我们可以做多个

firstValues = df.mul(firstPositions, axis=1)
tickers = ['EDP.LS', 'DIS', 'GILD', 'FB'] 

start_date = 'Your Start Date'
end_date = 'Your End Date'

exchange = 'yahoo'
column_name = 'Adj Close' # 'Open' 'High' 'Low' 'Close' 'Adj Close' 'Volume' #Your Columns


allData = pd.DataFrame()
finalTickers = []
for ticker in tickers:
    try:

        allData = pd.merge(allData, pd.DataFrame(pdr.get_data_yahoo(ticker, fields='price', 
                           start=start_date, end=end_date)['Adj Close']), 
                           right_index=True, left_index=True, how='outer')

        # Appends tickers which have data
        finalTickers.append(ticker)

    except: 
        next 

allData.columns = finalTickers
allData = allData.dropna(axis='columns')
allData

Then:然后:

s = allData.mul(firstPositions_as_dataframe, axis=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM