簡體   English   中英

Python/Pandas:在一個 dataframe 中搜索日期,並在另一個 dataframe 的列中返回具有匹配日期的值

[英]Python/Pandas: Search for date in one dataframe and return value in column of another dataframe with matching date

我有兩個數據框,一個帶有收益日期和市場前/市場后代碼,另一個帶有每日 OHLC 數據。 首先 dataframe df:

賺取日期 anncTod
103 2015-11-18 0900
104 2016-02-24 0900
105 2016-05-18 0900
... ………… …………
128 2022-03-01 0900
129 2022-05-18 0900
130 2022-08-17 0900

第二個 dataframe af:

約會時間 打開 高的 低的 體積
2005-01-03 36.3458 36.6770 35.5522 35.6833 3343500
............ ………… ………… ………… ........... ...........
2022-04-22 246.5500 247.2000 241.4300 241.9100 1817977

我想從第一個 dataframe 中獲取一個日期,並在第二個 dataframe 中找到開盤價和/或收盤價。 根據 anncTod 值,我想找到前一天的收盤價(如果 =0900)或第二天的開盤價和收盤價(否則)。 我將使用這些數字來計算隔夜、盤中和接近收盤的移動,這些移動將存儲在 df 的新列中。

我不確定如何搜索匹配值並從該行但不同的列中獲取值。 我正在嘗試使用 df.iloc 和 for 循環來做到這一點。

這是完整的代碼:

import pandas as pd
import requests 
import datetime as dt

ticker = 'TGT'

## pull orats earnings dates and store in pandas dataframe
url = f'https://api.orats.io/datav2/hist/earnings.json?token=keyhere={ticker}'
response = requests.get(url, allow_redirects=True)

data = response.json()
df = pd.DataFrame(data['data'])

## reduce number of dates to last 28 quarters and remove updatedAt column
n = len(df.index)-28
df.drop(index=df.index[:n], inplace=True)
df = df.iloc[: , 1:-1]

## import daily OHLC stock data file
loc = f"C:\\Users\\anon\\Historical Stock Data\\us3000_tickers_daily\\{ticker}_daily.txt"
af = pd.read_csv(loc, delimiter=',', names=['Datetime','Open','High','Low','Close','Volume'])


## create total return, overnight and intraday columns in df
df['Total Move'] = '' ##col #2
df['Overnight'] = ''  ##col #3
df['Intraday'] = ''   ##col #4

for date in df['earnDate']:
    if df.iloc[date,1] == '0900':
        priorday = af.loc[af.index.get_loc(date)-1,0]
        priorclose = af.loc[priorday,4]
        open = af.loc[date,1]
        close = af.loc[date,4]
        df.iloc[date,2] = close/priorclose
        df.iloc[date,3] = open/priorclose
        df.iloc[date,4] = close/open
    else:
        print('afternoon')

我收到一個錯誤:

if df.iloc[date,1] == '0900':
ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types

將日期列轉換為整數會產生另一個錯誤。 有沒有更好的方法我應該 go 這樣做?

理想的 output 看起來像(組成數字,縮寫輸出):

賺取日期 anncTod 總移動 隔夜搬家 盤中走勢
2015-11-18 0900 9% 7.2% 1.8%

但將包括第一個 dataframe 中給出的所有日期。

更新

我將 df.iloc 換成了 df.loc,這似乎解決了這個問題。 新問題是在第二個 dataframe af 中搜索變量“日期”。 我已經簡化了代碼,以便在排除故障時僅打印“打開”列中的值。

這是更新和簡化的代碼(其他所有內容保持不變):

import pandas as pd
import requests 
import datetime as dt

ticker = 'TGT'

## pull orats earnings dates and store in pandas dataframe
url = f'https://api.orats.io/datav2/hist/earnings.json?token=keyhere={ticker}'
response = requests.get(url, allow_redirects=True)

data = response.json()
df = pd.DataFrame(data['data'])

## reduce number of dates to last 28 quarters and remove updatedAt column
n = len(df.index)-28
df.drop(index=df.index[:n], inplace=True)
df = df.iloc[: , 1:-1]

## set index to earnDate
df = df.set_index(pd.DatetimeIndex(df['earnDate']))

## import daily OHLC stock data file
loc = f"C:\\Users\\anon\\Historical Stock Data\\us3000_tickers_daily\\{ticker}_daily.txt"
af = pd.read_csv(loc, delimiter=',', names=['Datetime','Open','High','Low','Close','Volume'])


## create total return, overnight and intraday columns in df
df['Total Move'] = '' ##col #2
df['Overnight'] = ''  ##col #3
df['Intraday'] = ''   ##col #4

for date in df['earnDate']:
    if df.loc[date, 'anncTod'] == '0900':
        print(af.loc[date,'Open']) ##this is line generating error
    else:
        print('afternoon')

我現在得到 KeyError:'2015-11-18'

要使用loc訪問某一行,假設您搜索的 label 在索引中。 具體來說,這意味着您需要將日期列設置為索引。 前任:

import pandas as pd

df = pd.DataFrame({'earnDate': ['2015-11-18', '2015-11-19', '2015-11-20'],
                   'anncTod': ['0900', '1000', '0800'],
                   'Open': [111, 222, 333]})

df = df.set_index(df["earnDate"])

for date in df['earnDate']:
    if df.loc[date, 'anncTod'] == '0900':
        print(df.loc[date, 'Open'])

# prints
# 111

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM