Pandas计算电影ROI列时逻辑错误排查求助
Pandas计算电影ROI列时逻辑错误排查求助
我手头有一份电影财务相关的Pandas DataFrame,先给大家看下数据集的基本信息:
<class 'pandas.core.frame.DataFrame'> RangeIndex: 44691 entries, 0 to 44690 Data columns (total 22 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 44691 non-null int64 1 title 44691 non-null object 2 tagline 20284 non-null object 3 release_date 44657 non-null datetime64[ns] 4 genres 42586 non-null object 5 belongs_to_collection 4463 non-null object 6 original_language 44681 non-null object 7 budget_musd 8854 non-null float64 8 revenue_musd 7385 non-null float64 9 production_companies 33356 non-null object 10 production_countries 38835 non-null object 11 vote_count 44691 non-null float64 12 vote_average 42077 non-null float64 13 popularity 44691 non-null float64 14 runtime 43179 non-null float64 15 overview 43740 non-null object 16 spoken_languages 41094 non-null object 17 poster_path 44467 non-null object 18 cast 42502 non-null object 19 cast_size 44691 non-null int64 20 crew_size 44691 non-null int64 21 director 43960 non-null object dtypes: datetime64[ns](1), float64(6), int64(3), object(12) memory usage: 7.5+ MB
我重点关注两个财务字段:
- budget_musd:电影预算(单位:百万美元)
- revenue_musd:电影总票房收入(单位:百万美元)
我想要新增一个ROI列,计算公式是revenue_musd / budget_musd,同时做了空值和零值的判断:如果预算/收入为空,或者其中任意一个为0,就返回0。于是写了下面的函数并应用到DataFrame上:
import pandas as pd def calculate_roi(row): if pd.isna(row['budget_musd']) or pd.isna(row['revenue_musd']): return 0 elif row['budget_musd'] == 0.00 or row['revenue_musd'] == 0.00: return 0 else: return row['revenue_musd'] / row['budget_musd'] df['ROI'] = df.apply(lambda row: calculate_roi(row), axis=1)
但现在遇到了逻辑错误:我明明定义了当分母(budget_musd)为0时ROI返回0,但实际结果不对。比如看索引为3965的行(我一开始标注的是行3976,实际是3965):
id 13703 title Less Than Zero tagline In Beverly Hills, you can have anything your heart desires. You just can't have it the way it used to be. release_date 1987-11-06 00:00:00 genres Drama|Crime|Romance belongs_to_collection NaN original_language en budget_musd 0.00 revenue_musd 12.40 production_companies Twentieth Century Fox Film Corporation|Amercent Films|American Entertainment Partners L.P. production_countries United States of America vote_count 77.00 vote_average 6.10 popularity 4.03 runtime 98.00 overview A college freshman returns to Los Angeles for the holidays at his ex-girlfriend's request, but discovers that his former best friend has an out-of-control drug habit. spoken_languages English|Deutsch|Español poster_path <img src='http://image.tmdb.org/t/p/w185//1GY0ZhAxOR2RgxGnOkeKoKb2mFM.jpg' style='height:100px;'> cast Andrew McCarthy|Jami Gertz|Robert Downey Jr.|James Spader|Brad Pitt|Tony Bill|Nicholas Pryor|Michael Bowen|Sarah Buxton|Donna Mitchell cast_size 10 crew_size 3 director Marek Kanievska profit 12.40 ROI 12396383.00 Name: 3965, dtype: object
这一行的budget_musd是0.00,按照我的函数逻辑应该返回0,但实际得到的ROI是12396383.00,完全不符合预期。有没有大佬能帮我排查下问题出在哪里?
备注:内容来源于stack exchange,提问作者majid Hakimi
相关产品推荐
相关产品推荐

