【发布时间】:2018-07-24 22:42:36
【问题描述】:
我有一个这样的数据框 df
project_ID country prj_start prj_end revenue profit
2131 USA 201603 201703 100000 30000
5124 UK 201502 201606 1500 1000
1245 UK 201010 201710 1800 1000
我想找出每个月和国家/地区的活跃项目数量,并将它们的收入和利润相加。输出看起来像这样
Month country active_projects revenue profit
201603 USA 15 500000 100000
201603 UK 20 150000 100000
201604 Germany 30 1000000 500000
我的第一个编程语言是 C++,所以我倾向于使用循环来做事。我几乎成功地创建了这样的月槽。
#making a monthlist dataframe with count column to hold no. of active projects
monthlist = pd.DataFrame(columns= ["months","count"])
#making a new dataframe to insert the results into
newdf = pd.DataFrame(columns=["month", "country","active_prj_count","rev","gp"])
#making the month slots, not concerned with future values
monthlist['months']=pd.date_range(start = min(df['prj_start']), end =datetime.date.today(), freq='M').map(lambda x: 100*x.year + x.month)
monthlist['count']=0
#traversing through the original dataframe and monthlist to insert a new row into newdf
#everytime the project start is less than and prj end is greater than the month slot
i=0
for y in range(len(df)):
for x in range(len(monthlist)):
if(df.loc[y,'prj_start']<=monthlist.loc[x,'months'] & df.loc[y,'prj_end']>=monthlist.loc[x,'months']):
monthlist.loc[x,'count']=monthlist.loc[x,'count']+1
newdf.loc[i] = [monthlist.loc[x,'months'],df.loc[y,'country']
,monthlist.loc[x,'count'],df.loc[y,'revenue'],df.loc[y,'profit']]
i=i+1
这个解决方案有效,但我不得不承认它不是很聪明,计算效率也不是很高。需要一段时间来处理。任何有想法通过可能使用 pandas 或 numpy 函数来改进代码的人?
【问题讨论】:
-
你的数据框有多大?如果不是很大,一种解决方案是创建一个新列,其中包含开始和结束之间所有月份的列表。然后展开数据框,以便每个项目的每个月都有一个单独的行。然后,最后做一个简单的 groupby。
-
你的月份名称真的那么不规则吗?您似乎混合了缩写和写出的名称。而且我不明白这上面有什么顺序(您似乎将它们与
<进行比较,那么它们的类型是什么,str?) -
@Graipher,我仅通过 map 函数将日期转换为包含月份和年份的整数。这使得比较更简单。所以实际上月份就像 201005、201507 (YYYYMM)。我将在原帖中进行编辑。
-
这将使您大部分时间到达那里,但您需要考虑跨多个月的项目。
df.groupby(['pr_start','country']).agg({'projectid':'count', 'revenue': 'sum', 'profit': 'sum'}).rename(columns={'projectid':'Active Projects'}) -
我刚刚意识到我所说的与@jp_data_analysis 基本相同。一旦你将每个月分成单独的行,然后运行类似于我展示的 groupby 的东西。你快到了!
标签: python python-3.x python-2.7 pandas numpy