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 Pandas中DataFrame.drop_duplicates()删除重复值详解

    Python Pandas中DataFrame.drop_duplicates()删除重复值详解

    在实际处理数据中,数据预处理操作中,常常需要去除掉重复的数据,这篇文章主要给大家介绍了关于Python Pandas中DataFrame.drop_duplicates()删除重复值的相关资料,需要的朋友可以参考下
    2022-07-07
  • Python  中的pass语句语法详析

    Python  中的pass语句语法详析

    这篇文章主要介绍了Python 中的pass语句语法详析,pass是一种空操作(null operation),解释器执行到它的时候,除了检查语法是否合法,什么也不做就直接跳过
    2022-07-07
  • python 一个figure上显示多个图像的实例

    python 一个figure上显示多个图像的实例

    今天小编就为大家分享一篇python 一个figure上显示多个图像的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • Pandas 透视表和交叉表的实现示例

    Pandas 透视表和交叉表的实现示例

    本文主要介绍了Pandas 透视表和交叉表的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-07-07
  • Python海龟绘图之绘制趣味简笔画

    Python海龟绘图之绘制趣味简笔画

    大家好,本篇文章主要讲的是Python海龟绘图之绘制趣味简笔画,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下,方便下次浏览
    2021-12-12
  • 浅述python2与python3的简单区别

    浅述python2与python3的简单区别

    python2:print语句,语句就意味着可以直接跟要打印的东西而python3:print函数,函数就以为这必须要加上括号才能调用。下面通过本文给大家介绍python2与python3的简单区别,感兴趣的朋友跟随小编一起看看吧
    2018-09-09
  • Python中axis=0与axis=1指的方向有什么不同详解

    Python中axis=0与axis=1指的方向有什么不同详解

    对数据进行操作时,经常需要在横轴方向或者数轴方向对数据进行操作,这时需要设定参数axis的值,下面这篇文章主要给大家介绍了关于Python中axis=0与axis=1指的方向有什么不同的相关资料,需要的朋友可以参考下
    2024-01-01
  • Django 路由控制的实现代码

    Django 路由控制的实现代码

    这篇文章主要介绍了Django 路由控制的实现代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-11-11
  • 基于pytorch的lstm参数使用详解

    基于pytorch的lstm参数使用详解

    今天小编就为大家分享一篇基于pytorch的lstm参数使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • Python Requests模拟登录实现图书馆座位自动预约

    Python Requests模拟登录实现图书馆座位自动预约

    这篇文章主要为大家详细介绍了Python Requests的模拟登录,Python实现图书馆座位自动预约,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-04-04

最新评论