【问题标题】:Comparing misaligned Series object比较未对齐的系列对象
【发布时间】:2018-09-10 19:32:45
【问题描述】:

我有一些带时间戳的财务数据,如下所示:

样本数据:

transaction_type transaction_announced_date transaction_size_USDmm target_company_name ------------------ ---------------- ---- ------------------ --------- B 2017 年 11 月 12 日 8000 公司 A A 2017 年 4 月 19 日 NULL 公司 A A 2/12/2016 200 公司 A A 2016 年 5 月 24 日 NULL 公司 A A 2016 年 6 月 1 日 3500 公司 A B 2016 年 7 月 7 日 NULL 公司 A A 2016 年 9 月 22 日 30 公司 A A 2014 年 12 月 4 日 2800 公司 A A 2015 年 1 月 16 日 1691 公司 B A 2015 年 3 月 22 日 NULL 公司 B B 2015 年 7 月 31 日 1000 公司 C A 8/19/2015 NULL 公司 C A 2015 年 8 月 25 日 NULL 公司 C

对于有交易 B 的公司,我想找到该公司之前交易 A 的总和(基于公布的日期),并将该值添加到名为“sum_prior_trans_A”的新列中。

预期结果:

transaction_type transaction_announced_date transaction_size_USDmm target_company_name sum_prior_trans_A ------------------ ---------------- ---- ----------------- --------- --------- ---------- B 2017 年 11 月 12 日 8000 公司 A 6530 B 2016 年 7 月 7 日 NULL 公司 A 2830 B 2015 年 7 月 31 日 1000 公司 C NaN

目前的做法:

#input dataframe
trans_data

#add a new column that is the sum of all prior transactions A. 
#Will later drop all transactions A rows to be only left with transactions B as desired.  
trans_data['sum_previous_private_placements'] = trans_data.groupby(['target_company_name', 'transaction_type', 'transaction_announced_date']).filter(lambda row: (trans_data['target_company_name'] == row['target_company_name']) & (trans_data['transaction_announced_date'] == row['transaction_announced_date']) & (trans_data['transaction_type'] == 'A'))['transaction_size_USDmm'].sum()

我收到以下错误:

ValueError: 只能比较标签相同的 Series 对象

如何找到每行(公司)的先前事务 A 的总和,并将该值添加到名为“sum_prior_trans_A”的新列中,而不会遇到未对齐的 Series 对象错误?

【问题讨论】:

标签: python pandas


【解决方案1】:

想出了一种方法。我相信还有更有效的方法。

#df of companies that have had transaction B
companies_with_trans_B = trans_data[trans_data['transaction_type'] == 'Merger/Acquisition']
companies_with_trans_B.reset_index(drop=True, inplace=True)  

#method for adding transaction A amounts for a given company and till a given date
def sum_previous_private_placements(df1, company_name, announced_date):
    return df1[(df1['target_company_name'] == company_name) & (df1['transaction_type'] == 'A') & (df1['transaction_announced_date'] <= announced_date)]['transaction_size_USDmm'].sum()  

#loop through companies_with_trans_B and call sum_previous_private_placements()
for i in companies_with_trans_B.index:
    companies_with_trans_B.loc[i, 'sum_previous_private_placements'] = sum_previous_private_placements(trans_data,companies_with_trans_B.loc[i,'target_company_name'], companies_with_trans_B.loc[i, 'transaction_announced_date'])

【讨论】:

    猜你喜欢
    • 2020-01-31
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2022-06-26
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    相关资源
    最近更新 更多