[英]can anyone explain to me why this apply() method isn't working?
这不起作用:
def rator(row):
if row['country'] == 'Canada':
row['stars'] = 3
elif row['points'] >= 95:
row['stars'] = 3
elif row['points'] >= 85:
row['stars'] = 2
else:
row['stars'] = 1
return row
with_stars = reviews.apply(rator, axis='columns')
但这有效:
def rator(row):
if row['country'] == 'Canada':
return 3
elif row['points'] >= 95:
return 3
elif row['points'] >= 85:
return 2
else:
return 1
with_stars = reviews.apply(rator, axis='columns')
我正在练习 Kaggle,并阅读他们的教程和文档。 我对这个概念有点困惑。
我知道apply()
方法作用于 DataFrame 的整行,而map()
作用于列中的每个元素。 并且它应该返回一个 DataFrame,而map()
返回一个系列。
只是不确定这里的机制是如何工作的,因为它不允许我返回 function 内的行......
一些数据:
country description designation points price province region_1 region_2 taster_name taster_twitter_handle title variety winery
0 Italy Aromas include tropical fruit, broom, brimston... Vulkà Bianco -1.447138 NaN Sicily & Sardinia Etna NaN Kerin O’Keefe @kerinokeefe Nicosia 2013 Vulkà Bianco (Etna) White Blend Nicosia
1 Portugal This is ripe and fruity, a wine that is smooth... Avidagos -1.447138 15.0 Douro NaN NaN Roger Voss @vossroger Quinta dos Avidagos 2011 Avidagos Red (Douro) Portuguese Red Quinta dos Avidagos
Index(['country', 'description', 'designation', 'points', 'price', 'province',
'region_1', 'region_2', 'taster_name', 'taster_twitter_handle', 'title',
'variety', 'winery'],
dtype='object')
https://www.kaggle.com/residentmario/summary-functions-and-maps
官方文档 state:
改变传递的 object 的函数可能会产生意外行为或错误,因此不受支持
看来您正在做一些明确禁止的事情。 尝试 append 之后调用apply
的星星数据
您不应将apply
与修改输入的 function 一起使用。 您可以将代码更改为:
def rator(row):
new_row = row.copy()
if row['country'] == 'Canada':
new_row['stars'] = 3
elif row['points'] >= 95:
new_row['stars'] = 3
elif row['points'] >= 85:
new_row['stars'] = 2
else:
new_row['stars'] = 1
return new_row
with_stars = reviews.apply(rator, axis='columns')
但是,只返回您关心的列而不是返回整个 dataframe 只是为了更改一列更简单。 如果您编写rator
只返回一列,但您想要完整的 dataframe,您可以使用with_stars = reviews.copy()
然后with_stars['stars'] = reviews.apply(rator, axis='columns')
. 此外,如果if
分支以 return 结束,您可以在它之后执行if
而不是elif
。 您还可以使用cut
简化代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.