如何在Pandas中根据条件替换列中的值?

本文介绍了如何在Python的Pandas库中使用loc、NumPy.where、mask和apply与lambda函数根据条件替换DataFrame列的值,通过实例展示了这些方法的应用。
摘要由CSDN通过智能技术生成

在使用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
  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值