【问题标题】:Conditional Looping through Dataframe通过数据框进行条件循环
【发布时间】:2021-05-08 04:06:39
【问题描述】:

我在尝试循环数据帧时遇到了问题。我想要做的是,根据特定列中的字符串,给新列一个特定的值,然后重复行 x 次。否则,给该新列另一个值并重复 y 次。但是,当我尝试我的代码时,我收到以下问题:

ValueError:“数组长度 1 与索引长度 5 不匹配”。

我不确定我的逻辑有什么问题,并且想知道是否有人可以告诉我如何解决这个障碍。非常感谢您的帮助!

请在下面找到我的代码:

for x in df['GP Line Item Code:']:
    if x == "PS-AFS":
        lens = 1
        clientDetails = pd.DataFrame({'Billing Date': np.repeat(df['Billed Date'], lens),
                    'Invoice #': np.repeat(df['GREAT PLAINS INV #'], lens),
                    'Customer #': np.repeat(df['GP Code'], lens),
                    'Customer Name': np.repeat(df['Client'], lens),
                    'Transaction ID': np.repeat(df['Quote ID'], lens),
                    'Description': np.repeat(df['Task'], lens),
                    'Department Group': np.repeat(df['Dept'], lens),
                    'Product Family': np.repeat(df['GP Line Item Code:'], lens),
                    'Revenue Type': np.repeat("Service", lens),
                    'Rev Rec Year': np.repeat(df['Billed Date'].dt.year, lens)
                   }
                  )
    else:
        lens = 12
        clientDetails = pd.DataFrame({'Billing Date': np.repeat(df['Billed Date'], lens),
                    'Invoice #': np.repeat(df['GREAT PLAINS INV #'], lens),
                    'Customer #': np.repeat(df['GP Code'], lens),
                    'Customer Name': np.repeat(df['Client'], lens),
                    'Transaction ID': np.repeat(df['Quote ID'], lens),
                    'Description': np.repeat(df['Task'], lens),
                    'Department Group': np.repeat(df['Dept'], lens),
                    'Product Family': np.repeat(df['GP Line Item Code:'], lens),
                    'Revenue Type': np.repeat("Maintenance", lens),
                    'Rev Rec Year': np.repeat(df['Billed Date'].dt.year, lens)
                   }
                  )

我的逻辑是,对于数据框中的记录,请查看 GP 行项目代码。如果 GP 行项目代码为 PS-AFS,则将每条记录重复 1 次,并将收入类型标记为服务。否则,对于不是 PS-AFS 的所有其他记录,因此我的所有维护记录,将每条记录重复 12 次,并将收入类型标记为维护。感谢大家的帮助!

【问题讨论】:

    标签: python pandas numpy loops conditional-statements


    【解决方案1】:

    没有示例数据,我无法验证此代码,但它应该可以工作:

    mask = df['GP Line Item Code:'] == 'PS-AFS'
    
    out = pd.concat([df.loc[mask].assign(Revenue_Type='Sevice')] +
                    [df.loc[~mask].assign(Revenue_Type='Maintenance')]*12)
    

    然后您可以重命名列或创建新列。

    【讨论】:

      猜你喜欢
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 2022-10-14
      • 2022-01-20
      • 2020-07-01
      • 1970-01-01
      相关资源
      最近更新 更多