【问题标题】:Doing a loop calculation进行循环计算
【发布时间】:2021-12-10 13:05:12
【问题描述】:

toto =

C1Date C1Type C2Date C2Type ..... C10Date CType10 PolDate
dd-mm-yyyy :Proposer NaT NaN NaT NaN dd-mm-yyyy
dd-mm-yyyy :Proposer NaT NaN NaT NaN dd-mm-yyyy
dd-mm-yyyy :Other dd-mm-yyyy Proposer NaT NaN dd-mm-yyyy
dd-mm-yyyy :Proposer NaT NaN NaT NaN dd-mm-yyyy
dd-mm-yyyy :Other dd-mm-yyyy Other NaT NaN dd-mm-yyyy

其中C 指的是Claim 等等。即连续最多有 10 个Claims

我需要确定是否有任何 Claims 来自 Proposer,并且对于这些声明,它们是否在 PolDate 之后的 3 年内发生(PolDate 总是大于任何 Cdate

我能够执行以下操作,但无法让日期减法在循环内工作:

CLM = {}

for i in range(1 , 11):
    

    CLM[i] = toto.loc[toto[f'C{i}Type'] == 'Proposer']
    
    #can't get this date subtraction to work within the loop. But can do the subtraction outside of the loop.

    CLM[i]['diff'] = (CLM[i]['PolDate'].sub(CLM[i][f'C{i}Date'], 
    axis=0)).dt.days
   
    use_cols = ['CustomerID',  f'C{i}Type', f'C{1}Date', 'PolDate  ']
    CLM[i] = CLM[i][use_cols]
    
    print("Claim:" + f'{i}' +" "+ str(CLM[i].shape))

错误:

试图在 DataFrame 中的切片副本上设置值。尝试 使用 .loc[row_indexer,col_indexer] = value 代替

此外,无法进行 3 年比较:

if (CLM[1]['diff'] > 1095): 
    #1095 = (365 * 3):
    CLM[1]['CLMLAST3'] = 0
else:
    CLM[1]['diff'] = 1

错误:

ValueError:Series 的真值不明确。使用 a.empty, a.bool()、a.item()、a.any() 或 a.all()。

【问题讨论】:

标签: python pandas datetime logical-operators


【解决方案1】:

简而言之,试试这个,它对我有用:(对 pandas 了解不多,所以也许效率是你的领域,我只是从发布的代码中删除了错误)

CLM = {}

for i in range(1 , 11):
    

    CLM[i] = toto.loc[toto[f'C{i}Type'] == 'Proposer']
    
    #can't get this date subtraction to work within the loop. But can do the subtraction outside of the loop.

    **CLM.get(i).loc[:, 'diff'] = (pd.to_datetime(CLM[i]['PolDate'],format='%d-%m-%Y').sub(pd.to_datetime(CLM[i][f'C{i}Date'],format='%d-%m-%Y'))).dt.days**
   
    use_cols = ['CustomerID',  f'C{i}Type', f'C{1}Date', 'PolDate  ']
    CLM[i] = CLM[i][use_cols]
    
    print("Claim:" + f'{i}' +" "+ str(CLM[i].shape))

注意事项:

  1. 警告“试图在 DataFrame 的切片副本上设置值。尝试使用 .loc[row_indexer,col_indexer] = value 代替”也出现在此代码中.因为 CLM[i]['diff'] 与 CLM[i].loc['diff'] 不同。见这里:https://stackoverflow.com/a/53954986/5772008

  2. CLM[i]['PolDate'] 是字符串的“列表”,因此您不能从字符串中减去字符串,但可以从另一个字符串中减去 pandas 日期时间对象。因此,首先将它们转换为日期时间对象,然后减去。

您的额外问题也是如此,您将列表与值进行比较,请参阅https://stackoverflow.com/a/53830333/5772008 简而言之,您很可能想要这样:“if (CLM[1]['diff'].all() > 1095)”,因此它会将序列中的每个值而不是整个序列与一个值进行比较。

【讨论】:

  • 谢谢!行得通。
  • 我想摆脱警告。我之前使用了一个导入步骤: pd.read_csv( 'xxx.csv', index_col = 0, dtype{"C1Type" : "string", ... , }, parse_dates = ["CDate1", ..., “CDate10”,“PolDate”])(我认为这会整理数据)。日期的 dtype 返回为 '
猜你喜欢
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多