python更新pandas_Python Pandas:根据另一列的值更新行

I have a pandas dataframe, df, like:

name | grade | grade_type

---------------------------

sarah | B | letter

alice | A | letter

eliza | C | letter

beth | 76 | numeral

jones | 90 | numeral

All values in df are strings, including the numbers. I want to convert the grade numeric values into letters, based on checking the grade_type column, to get:

name | grade | grade_type

---------------------------

sarah | B | letter

alice | A | letter

eliza | C | letter

beth | B | numeral

jones | A | numeral

For completeness, the numeral-to-letter grade conversions are:

A: grade > 80

B: 70 < grade <= 80

C: 60 < grade <= 70

Why doesn't this work?

for index, row in df.iterrows():

if row.grade_type == "numeral":

grade_val = int(row.grade.values[0])

if grade_val > 80:

row.grade = "A" # This assignment doesn't update row.grade!

elif...

The alternative is using df.apply(...lambda:...), but I'm not too sure how to pull that off, since we have to check the grade_type column before deciding whether or not to update the grade value.

解决方案

The reason that your DataFrame doesn't update is because rows returned from iterrows(): are copies. And you're working on that copy.

You can use the index returned from iterrows and manipulate DataFrame directly:

for index, row in df.iterrows():

grade_val = int(row.grade.values[0])

if grade_val > 80:

df.loc[index, 'grade'] = 'A'

...

Or as you said you can use df.apply(), and pass it a custom function:

def get_grades(x):

if x['grade_type'] == 'letter':

return(x['grade_val'])

if x['grade_val'] > 80:

return "A"

...

df['grade'] = df.apply(lambda x: get_grades(x), axis=1)

You can also use if else in your lambda to check if x['grade_type'] is numeric as follows, use the one that looks easier to read.

def get_grades(grade_val):

if grade_val > 80:

return "A"

...

df['grade'] = df.apply(lambda x: get_grades(x['grade'])

if x['grade_type'] == 'numeral' else x['grade'], axis=1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值