【问题标题】:Multiple filter criteria for a dataframe数据框的多个过滤条件
【发布时间】:2020-05-02 17:19:39
【问题描述】:

感谢@James,我有一个有效的过滤条件。 我现在尝试创建一个脚本,允许我上传包含股票代码和发行日期列表的数据文件。 因此,我想在过滤器函数上迭代列表。 但是,我不断得到

IndexError: index 0 is out of bounds for axis 0 with size 0

有什么办法可以解决这个问题吗? 见下面的脚本和函数:

过滤功能:

import pandas as pd
from datetime import datetime
import urllib
import datetime

def get_data(issue_date, stock_ticker):
    df = pd.read_csv (r'D:\Project\Data\Short_Interest\mergedshort.csv')
    df['Date'] = pd.to_datetime(df['Date'], format="%Y%m%d")
    d = df

    df = pd.DataFrame(d)
    short = df.loc[df.Symbol.eq(stock_ticker)]
    # get the index of the row of interest
    ix = short[short.Date.eq(issue_date)].index[0]
    # get the item row for that row's index
    iloc_ix = short.index.get_loc(ix)
    # get the +/-1 iloc rows (+2 because that is how slices work), basically +1 and -1 trading days
    short_data = short.iloc[iloc_ix-10: iloc_ix+11]
    return [short_data]

以及进行迭代和上传列表的脚本(其中包含“issue_dates”和“stock_tickers”的列表)

import shortdatafilterfinal
import csv
import tkinter as tk
from tkinter import filedialog

# SHORT DATA trading day time series
# Open File Dialog
# iterates the stock tickers and respective dates over the filter function

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()

# Load Spreadsheet data
f = open(file_path)

csv_f = csv.reader(f)
next(csv_f)

result_data = []

# Iterate
for row in csv_f:
    try:
       return_data = shortdatafilterfinal.get_data(row[1], row[0])
       if len(return_data) != 0:
          # print(return_data)
          result_data_loc = [row[1], row[0]]
          result_data_loc.extend(return_data)
          result_data.append(result_data_loc)
    except AttributeError:
          print(row[0])
          print('\n\n')
          print(row[1])
          continue

if result_data is not None:
    with open('resultsshort.csv', mode='w', newline='') as result_file:
        csv_writer = csv.writer(result_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        for result in result_data:
            # print(result)
            csv_writer.writerow(result)
else:
    print("No results found!")

【问题讨论】:

  • 您想从初始数据帧中获得 +/-1 行,还是从第一个过滤器的结果中获得 +/-1 行?
  • 我希望 +/-1 来自第一个过滤器的结果,而不是来自初始数据帧
  • @James,希望清楚吗?

标签: python arrays dataframe filter index-error


【解决方案1】:

您可以使用.iloc 查看过滤结果的项目索引。

import pandas as pd

d = {'Date':['2011-01-03', '2011-01-03', '2011-01-03','2011-01-06', '2011-01-06', 
             '2011-01-06', '2011-01-08', '2011-01-08','2011-01-08', '2011-01-12', 
             '2011-01-12', '2011-01-12'], 
     'Symbol':['ARAY', 'POLA', 'AMRI', 'ARAY', 'POLA', 'AMRI', 'ARAY', 'POLA', 
               'AMRI', 'ARAY', 'POLA', 'AMRI']}
df = pd.DataFrame(d)

def look_around(df, symbol, date):
    short = df.loc[df.Symbol.eq(symbol)]
    # get the index of the row of interest
    ix = short[short.Date.eq(date)].index[0]
    # get the item row for that row's index
    iloc_ix = short.index.get_loc(ix)
    # get the +/-1 iloc rows (you have to use +2 because that is how slices work)
    return short.iloc[iloc_ix-1: iloc_ix+2]

look_around(df, 'ARAY', '2011-01-08')
# returns:
        Date Symbol
3 2011-01-06   ARAY
6 2011-01-08   ARAY
9 2011-01-12   ARAY

【讨论】:

  • 像魅力一样工作。因为我想把它变成一个我可以用来运行大量迭代的函数,所以我试着稍微修改一下代码,但我遇到了一个问题。除“issue_date”外,此功能应该可以工作。如何在 short.query 函数中实现 issue_date?我已经编辑了我的主要帖子@James
  • 为您添加了功能化版本。
  • 我遇到了一个新问题,试图让功能化版本发挥作用。但是,收到 indexerrors 并且不知道如何解决这个问题。
【解决方案2】:

如果我理解正确,您想从所选日期中选择 +/-1 行:

short = df.loc[df['Symbol'] == 'ARAY']

def get_date(df, d):
    v = short['Date']==d
    return df[v | v.shift(fill_value=False) | v.shift(-1,fill_value=False)]

print(get_date(short, '2011-01-08'))

打印:

         Date Symbol
3  2011-01-06   ARAY
6  2011-01-08   ARAY
9  2011-01-12   ARAY

【讨论】:

  • 使用了 James 提供的解决方案。我现在更进一步,遇到了 indexerror 问题。请参阅编辑后的主帖。
猜你喜欢
  • 2020-08-29
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多