Dataframe ValueError:具有多个元素的数组的真值不明确。使用a.any()或a.all()

2024-09-29 19:33:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧(reportingDatesDf),它的头看起来像这样:

reportingDatesDf.index            unique_stock_id reporting_type
date                                     
2015-01-28  BBG.MTAA.STM.S         2014:A
2015-01-28  BBG.MTAA.STM.S        2014:S2
2015-01-28  BBG.MTAA.STM.S        2014:Q4
2014-10-29  BBG.MTAA.STM.S        2014:C3
2014-10-29  BBG.MTAA.STM.S        2014:Q3

我正在尝试减少数据帧,以包含仅在两个日期之间的条目,并使用以下行:

^{pr2}$

使用以下代码从CSV创建数据帧:

def getReportingDatesData(rawStaticDataPath,startDate,endDate):
    pattern = 'ReportingDates'+ '.csv'
    staticPath = rawStaticDataPath

    with open(staticPath+pattern,'rt') as f:

         reportingDatesDf = pd.read_csv(f, 
                 header=None,
                 usecols=[0,1,2],
                 parse_dates=[1],
                 dayfirst=True,
                 index_col=[1],
                 names=['unique_stock_id','date','reporting_type'])       
         #print(reportingDatesDf.head())
         print('reportingDatesDf.index',reportingDatesDf)      
         reportingDatesDf = reportingDatesDf[(reportingDatesDf.index >= startDate) and (reportingDatesDf.index <= endDate)]

但是我得到了一个错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

有人能告诉我为什么会发生这种情况,因为我正在使用类似的代码,在其他地方工作,以及如何纠正问题请。在

谢谢


Tags: 数据代码iddateindextypestockunique
3条回答

尝试改变这个:

reportingDatesDf = reportingDatesDf[(reportingDatesDf.index >= startDate) and (reportingDatesDf.index <= endDate)]

为此:

^{pr2}$

换句话说,使用适当的运算符;)

在我看来像是在排队

reportingDatesDf = reportingDatesDf[(reportingDatesDf.index >= startDate) and (reportingDatesDf.index <= endDate)]

变量

^{pr2}$

是一个数组。因此,说

(reportingDatesDf.index >= startDate)

模棱两可。您需要指定是否检查数组中的所有值是否都大于startDate,或者是否包含任何大于startDate的值。将代码编辑为

reportingDatesDf = reportingDatesDf[any(reportingDatesDf.index >= startDate) and any(reportingDatesDf.index <= endDate)]

或者

reportingDatesDf = reportingDatesDf[all(reportingDatesDf.index >= startDate) and all(reportingDatesDf.index <= endDate)]

应该能解决这个问题。在

and不广播。它不能,因为它必须短路,而且做短路广播没有好的答案。在

如果需要执行元素操作and,则应该使用&。在

相关问题 更多 >

    热门问题