程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

For loop to convert strings based on last word not running

发布于2023-02-05 16:21     阅读(641)     评论(0)     点赞(30)     收藏(1)


I am trying to write a for-loop in python on a pandas dataframe. I want to convert all strings in the color column that have "Green" as their last word (ex. Yellowish Green") to just "Green". Below is my loop:

for color in df['color']:
    low = color.split()
    if low[-1] == "Green":
        color = "Green"

However, this is not changing the actual values in the dataframe.


解决方案


You can do:

def transform(string):
    last_word = string.split()[-1]
    if last_word.lower() == 'green':
        return 'green'
    else:
        return string

df['color'] = df['color'].apply(transform)


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/1895754/9953a6d0a636163fd264/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

30 0
收藏该文
已收藏

评论内容:(最多支持255个字符)