【问题标题】:Python define function to subset datafram by a condition in a specific columnPython通过特定列中的条件定义函数来子集数据框
【发布时间】:2020-03-20 16:44:26
【问题描述】:

试图创建一个函数来为每个扇区创建新的数据帧,但不确定我在函数的返回部分做错了什么。

这就是我为每个部门创建数字所做的工作。然后在我的数据中,我有一列 gsector,其中包含相应扇区的数字。希望这是有道理的。

# Create a list of the GICS Sectors 
Energy = 10
Materials = 15 
Industrials = 20
Consumer_Discretionary = 25
Consumer_Staples = 30
Health_Care = 35
Financials = 40
Information_Technology = 45
Communication_Services = 50
Utilities = 55
Real_Estate = 60

GICS_Sectors = [Energy,Materials,Industrials,Consumer_Discretionary,Consumer_Staples,Health_Care,Financials,Information_Technology,Communication_Services,Utilities,Real_Estate]
##############################################################################

def Sector_Subset(dataframe,GICS_Sectors):
    """
    This function takes a dataframe and will pull sector specific data 
    to create a new dataframe for each eactor

    Parameters:
        dataframe = Portfolio
        GICS_Sectors = Each 11 sectors

    Return:
        GICS_dataframe

    Notes:
        We want to do this so we can easily graph momentum separately to compare sectors
    """
        dataframe[['datadate','GVKEY','trt1m','gsector','Start_Date','Rank_Percentile','Buy_Date','Sell_Date']]
return [dataframe.groupby('gsector').get_group(d) for d in GICS_Sectors]


Energy_Portfolio = Sector_Subset(Portfolio,Energy)

【问题讨论】:

  • 你到底想做什么,为什么你认为这是错误的? stackoverflow.com/help/minimal-reproducible-example
  • 我要做的是定义函数,以便它根据 gsector 列中的 # 将大数据框 Portfolio 拆分为 11 个较小的数据框,我已经为名称 GICS_Sectors 创建了一个列表一旦我有了函数,我想创建一个循环来使用该函数来创建这 11 个数据帧

标签: python function subset finance


【解决方案1】:

最可能的错误出现在示例的最后一行

代替:

return [dataframe.get_group(d) for d in GICS_Sectors]

你应该写:

return [dataframe.groupby('gsector').get_group(d) for d in GICS_Sectors]

正如您之前提到的,您希望按“gsector”列对数据进行分组。但是,它没有在剪辑中的任何地方指定。我不是 100% 是你的问题 - 变量 Portfolio 和 Energy 没有被声明,所以我不得不猜测。

这是我的工作示例代码,其中包含数据框中的随机数据。

import pandas as pd

# Modified original function
def Sector_Subset(dataframe,GICS_Sectors):
    """
    This function takes a dataframe and will pull sector specific data 
    to create a new dataframe for each eactor

    Parameters:
        dataframe = Portfolio
        GICS_Sectors = Each 11 sectors

    Return:
        GICS_dataframe

    Notes:
        We want to do this so we can easily graph momentum separately to compare sectors
    """

dataframe[['datadate','GVKEY','trt1m',
           'gsector','Start_Date','Rank_Percentile',
           'Buy_Date','Sell_Date']]

    # Below is the suspected error
    return [dataframe.groupby('gsector').get_group(d) for d in GICS_Sectors]
    # Original code
    # return [dataframe.get_group(d) for d in GICS_Sectors]

# Example data
Portfolio = {'datadate':['2020-03-20', '2020-03-19', '2020-03-18', '2020-03-17'],
        'GVKEY':[201, 211, 191, 181],
        'trt1m':[202, 212, 192, 182],
        'gsector':['Italy', 'Poland', 'Germany', 'Italy'],
        'Start_Date':['2020-03-15', '2020-02-19', '2020-03-13', '2020-03-11'],
        'End_Date':['2020-03-16', '2020-03-19', '2020-03-16', '2020-03-12'],
        'Rank_Percentile':['30th', '40th', '45th', '29th'],
        'Buy_Date':['2020-03-15', '2020-03-15', '2020-03-15', '2020-03-15'],
        'Sell_Date':['2020-03-17', '2020-03-18', '2020-03-165', '2020-03-15']}

# Test the function
Portfolio = pd.DataFrame(Portfolio)
Energy = ['Italy', 'Poland', 'Germany']
Energy_Portfolio = Sector_Subset(Portfolio, Energy)

# Print results
for enrg in Energy_Portfolio:
    print('\n')
    print(enrg)

【讨论】:

  • 所以我用新的代码行重新运行它并得到这个错误:TypeError: 'int' object is not iterable
  • 请编辑您的帖子并添加变量 EnergyPortfolio。您不必向我们展示真实数据,但如果不查看全貌,就很难找到错误。似乎您将 int 作为 Energy(例如 500)而不是列表或任何可迭代变量传递。
  • 我会尝试以这种方式调用您的函数:Energy_Portfolio = Sector_Subset(Portfolio,[Energy]) 您的代码中的 Energy 似乎是一个整数变量 - 这样您将创建一个包含一个元素的列表。如果 gsector 列中没有行具有来自 Energy 的值(在我的示例中为 500),它仍然会给您一个错误“KeyError: 500”。
  • 我刚刚添加了我如何定义每个部门..这仍然有效吗?
  • 这样行得通..但现在它的作用是将其变成一个包含数据框的列表...有没有办法让它直接进入数据框?
猜你喜欢
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 2020-02-24
  • 1970-01-01
  • 1970-01-01
  • 2016-05-14
  • 2016-08-08
  • 2016-07-02
相关资源
最近更新 更多