我正在尝试计算某个公司在其收益日期后一年内出现在新闻上的次数,并将该次数与其他人在同一时间段内进行比较。我有两个pandas数据帧,一个有收入日期,另一个有新闻。我的方法很慢。是否有更好的熊猫/ numpy方式?
import pandas as pd
companies = pd.DataFrame({'CompanyName': ['A', 'B', 'C'], 'EarningsDate': ['2013/01/15', '2015/03/25', '2017/05/03']})
companies['EarningsDate'] = pd.to_datetime(companies.EarningsDate)
news = pd.DataFrame({'CompanyName': ['A', 'A', 'A', 'B', 'B', 'C'],
'NewsDate': ['2012/02/01', '2013/01/10', '2015/05/13' , '2012/05/23', '2013/01/03', '2017/05/01']})
news['NewsDate'] = pd.to_datetime(news.NewsDate)
companies
看起来像
CompanyName EarningsDate
0 A 2013-01-15
1 B 2015-03-25
2 C 2017-05-03
news
看起来像
CompanyName NewsDate
0 A 2012-02-01
1 A 2013-01-10
2 A 2015-05-13
3 B 2012-05-23
4 B 2013-01-03
5 C 2017-05-01
我该如何重写?这有效,但是因为每个数据帧都是非常慢的。 500k行。
company_count = []
other_count = []
for _, company in companies.iterrows():
end_date = company.EarningsDate
start_date = end_date - pd.DateOffset(years=1)
subset = news[(news.NewsDate > start_date) & (news.NewsDate < end_date)]
mask = subset.CompanyName==company.CompanyName
company_count.append(subset[mask].shape[0])
other_count.append(subset[~mask].groupby('CompanyName').size().mean())
companies['12MonCompanyNewsCount'] = pd.Series(company_count)
companies['12MonOtherNewsCount'] = pd.Series(other_count).fillna(0)
最终结果companies
看起来像
CompanyName EarningsDate 12MonCompanyNewsCount 12MonOtherNewsCount
0 A 2013-01-15 2 2
1 B 2015-03-25 0 0
2 C 2017-05-03 1 0
答案 0 :(得分:2)
好的,这就是。
要获得companies['12MonCompanyNewsCount'] = pd.merge_asof(
news,
companies,
by='CompanyName',
left_on='NewsDate',
right_on='EarningsDate',
tolerance=pd.Timedelta('365D'),
direction='forward'
).groupby('CompanyName').count().NewsDate
,您可以使用file a JIRA,这非常简洁:
12MonOtherNewsCount
其效果大约是当前实施的两倍(并且会更好地扩展)
对于companies['12MonOtherNewsCount'] = companies.apply(
lambda x: len(
news[
(news.NewsDate.between(x.EarningsDate-pd.Timedelta('365D'), x.EarningsDate, inclusive=False))
&(news.CompanyName!=x.CompanyName)
]
),
axis=1
)
,我无法在没有循环的情况下找到一种方法。我想这有点简洁:
{{1}}
看起来确实快一点。
答案 1 :(得分:1)
我找不到一种不迭代companies
行的方法。但是,您可以为companies
设置开始日期列,迭代companies
行,并为符合您标准的news
的日期和公司名称创建布尔索引。然后只需执行布尔and
操作并对得到的布尔数组求和。
我发誓当你看到代码时会更有意义。
# create the start date column and the 12 month columns,
# fill the 12 month columns with zeros for now
companies['startdate'] = companies.EarningsDate - pd.DateOffset(years=1)
companies['12MonCompanyNewsCount'] = 0
companies['12MonOtherNewsCount'] = 0
# iterate the rows of companies and hold the index
for i, row in companies.iterrows():
# create a boolean index when the news date is after the start date
# and when the news date is before the end date
# and when the company names match
ix_start = news.NewsDate >= row.startdate
ix_end = news.NewsDate <= row.EarningsDate
ix_samename = news.CompanyName == row.CompanyName
# set the news count value for the current row of `companies` using
# boolean `and` operations on the indices. first when the names match
# and again when the names don't match.
companies.loc[i,'12MonCompanyNewsCount'] = (ix_start & ix_end & ix_samename).sum()
companies.loc[i,'12MonOtherNewsCount'] = (ix_start & ix_end & ~ix_samename).sum()
companies
#returns:
CompanyName EarningsDate startdate 12MonCompanyNewsCount \
0 A 2013-01-15 2012-01-15 1
1 B 2015-03-25 2014-03-25 0
2 C 2017-05-03 2016-05-03 1
12MonOtherNewsCount
0 2
1 1
2 0