Pandas根据条件实现替换列中的值

 更新时间:2024年01月17日 10:06:40   作者:python收藏家  
在使用Pandas的Python中,DataFrame列中的值可以通过使用各种内置函数根据条件进行替换,本文主要来和大家讨论在Pandas中用条件替换数据集列中的值的各种方法,希望对大家有所帮助

在使用Pandas的Python中,DataFrame列中的值可以通过使用各种内置函数根据条件进行替换。在本文中,我们将讨论在Pandas中用条件替换数据集列中的值的各种方法。

1. 使用dataframe.loc方法

使用此方法,我们可以使用条件或布尔数组访问一组行或列。如果我们可以访问它,我们也可以操纵值,是的!这是我们的第一个方法,通过pandas中的dataframe.loc[]函数,我们可以访问一个列并使用条件更改其值。

语法: df.loc[ df[“column_name”] == “some_value”, “column_name”] = “value”

注意:您也可以使用其他运算符来构造条件以更改数值。

例子:在此示例中,代码导入Pandas和NumPy库,从保存学生数据的字典(‘Student’)构建DataFrame(‘df’),然后在打印修改后的DataFrame之前将’gender’列的值从“male”更改为“1”。

# Importing the libraries
import pandas as pd
import numpy as np

# data
Student = {
	'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'],
	'gender': ['male', 'male', 'male', 'female', 'female', 'male'],
	'math score': [50, 100, 70, 80, 75, 40],
	'test preparation': ['none', 'completed', 'none', 'completed',
						'completed', 'none'],
}

# creating a Dataframe object
df = pd.DataFrame(Student)

# Applying the condition
df.loc[df["gender"] == "male", "gender"] = 1
print(df)

输出

 Name  gender  math score test preparation
0    John       1          50             none
1     Jay       1         100        completed
2  sachin       1          70             none
3  Geetha  female          80        completed
4  Amutha  female          75        completed
5  ganesh       1          40             none

2. 使用NumPy.where方法

我们将要看到的另一个方法是使用NumPy库。NumPy是一个非常流行的库,用于计算2D和3D数组。它为我们提供了一个非常有用的方法,where()可以访问带有条件的特定行或列。我们还可以使用此函数更改列的特定值。

语法: df[“column_name”] = np.where(df[“column_name”]==”some_value”, value_if_true, value_if_false)

例子:在此示例中,代码导入Pandas和NumPy库,从包含学生数据的名为“student”的字典中构建名为“df”的DataFrame,并使用NumPy np.where函数将“gender”列的值从“female”更改为“0”,将“male”更改为1。然后输出更改后的DataFrame。

# Importing the libraries
import pandas as pd
import numpy as np

# data
student = {
	'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'],
	'gender': ['male', 'male', 'male', 'female', 'female', 'male'],
	'math score': [50, 100, 70, 80, 75, 40],
	'test preparation': ['none', 'completed', 'none', 'completed',
						'completed', 'none'],
}

# creating a Dataframe object
df = pd.DataFrame(student)


# Applying the condition
df["gender"] = np.where(df["gender"] == "female", 0, 1)
print(df)

输出

Name  gender  math score test preparation
0    John       1          50             none
1     Jay       1         100        completed
2  sachin       1          70             none
3  Geetha       0          80        completed
4  Amutha       0          75        completed
5  ganesh       1          40             none

3. 使用mask方法

Pandas masking函数用于将任何行或列的值替换为条件。

语法: df[‘column_name’].mask( df[‘column_name’] == ‘some_value’, value , inplace=True )

例子:在此示例中,代码导入Pandas和NumPy库,从包含学生数据的名为“student”的字典中构建名为“df”的DataFrame,然后使用Pandas mask函数将“gender”列中的值“female”替换为0,然后打印修改后的DataFrame。它还包括一行注释,显示如何有条件地将“math score”列中的值替换为“good”(对于大于或等于60的分数)。

# Importing the libraries
import pandas as pd
import numpy as np

# data
student = {
	'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'],
	'gender': ['male', 'male', 'male', 'female', 'female', 'male'],
	'math score': [50, 100, 70, 80, 75, 40],
	'test preparation': ['none', 'completed', 'none', 'completed', 
						'completed', 'none'],
}

# creating a Dataframe object
df = pd.DataFrame(student)

# Applying the condition
df['gender'].mask(df['gender'] == 'female', 0, inplace=True)
print(df)
# Try this too
#df['math score'].mask(df['math score'] >=60 ,'good', inplace=True)

输出

Name gender  math score test preparation
0    John   male          50             none
1     Jay   male         100        completed
2  sachin   male          70             none
3  Geetha      0          80        completed
4  Amutha      0          75        completed
5  ganesh   male          40             none

4. 使用apply()和lambda函数

在这个例子中,我们使用了lamda和apply()函数来根据条件替换列中的值。

# Importing the libraries
import pandas as pd
import numpy as np

# Data
student = {
	'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'],
	'gender': ['male', 'male', 'male', 'female', 'female', 'male'],
	'math score': [50, 100, 70, 80, 75, 40],
	'test preparation': ['none', 'completed', 'none', 'completed',
						'completed', 'none'],
}

# Creating a DataFrame object
df = pd.DataFrame(student)

# Applying the condition using apply and lambda
df['gender'] = df['gender'].apply(lambda x: 0 if x == 'female' else x)

print(df)

输出

Name gender  math score test preparation 
0    John   male          50             none 
1     Jay   male         100        completed 
2  sachin   male          70             none 
3  Geetha      0          80        completed 
4  Amutha      0          75        completed 
5  ganesh   male          40             none

到此这篇关于Pandas根据条件实现替换列中的值的文章就介绍到这了,更多相关Pandas替换列值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python+OpenCV图片局部区域像素值处理改进版详解

    Python+OpenCV图片局部区域像素值处理改进版详解

    这篇文章主要为大家详细介绍了Python+OpenCV图片局部区域像素值处理的改进版,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-01-01
  • Python RabbitMQ消息队列实现rpc

    Python RabbitMQ消息队列实现rpc

    这篇文章主要介绍了python 之rabbitmq实现rpc,主要实现客户端通过发送命令来调用服务端的某些服务,服务端把结果再返回给客户端,感兴趣的小伙伴们可以参考一下
    2018-05-05
  • Django Admin实现三级联动的示例代码(省市区)

    Django Admin实现三级联动的示例代码(省市区)

    多级菜单在很多上面都有应用,这篇文章主要介绍了Django Admin实现三级联动(省市区),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-06-06
  • 用Python一键搭建Http服务器的方法

    用Python一键搭建Http服务器的方法

    今天小编就为大家分享一篇用Python一键搭建Http服务器的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-06-06
  • python搭建NPL模型的详细步骤和代码

    python搭建NPL模型的详细步骤和代码

    本文提供2026年最新中文NLP模型搭建教程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2026-04-04
  • Python异常处理操作实例详解

    Python异常处理操作实例详解

    这篇文章主要介绍了Python异常处理操作,结合实例形式分析了Python异常处理的相关原理、操作语句与使用技巧,需要的朋友可以参考下
    2018-05-05
  • python批量转换word文档为pdf文件的示例代码

    python批量转换word文档为pdf文件的示例代码

    这篇文章主要为大家详细介绍了如何使用python编写一个批量转换word文档为pdf文件的工具,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下
    2025-12-12
  • pip install jupyterlab失败的原因问题及探索

    pip install jupyterlab失败的原因问题及探索

    在学习Yolo模型时,尝试安装JupyterLab但遇到错误,错误提示缺少Rust和Cargo编译环境,因为pywinpty包需要它们来编译,由于在conda环境下操作,Rust和Cargo已经安装,问题是pywinpty包丢失,安装pywinpty包后,再次执行pip install jupyterlab即可正常下载
    2025-02-02
  • Python异常模块traceback用法实例分析

    Python异常模块traceback用法实例分析

    这篇文章主要介绍了Python异常模块traceback用法,结合实例形式分析了Python异常模块traceback的基本功能、使用方法及相关操作注意事项,需要的朋友可以参考下
    2019-10-10
  • python决策树之CART分类回归树详解

    python决策树之CART分类回归树详解

    这篇文章主要为大家详细介绍了python决策树之CART分类回归树,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-12-12

最新评论