Pandas根據(jù)條件實現(xiàn)替換列中的值
在使用Pandas的Python中,DataFrame列中的值可以通過使用各種內(nèi)置函數(shù)根據(jù)條件進行替換。在本文中,我們將討論在Pandas中用條件替換數(shù)據(jù)集列中的值的各種方法。
1. 使用dataframe.loc方法
使用此方法,我們可以使用條件或布爾數(shù)組訪問一組行或列。如果我們可以訪問它,我們也可以操縱值,是的!這是我們的第一個方法,通過pandas中的dataframe.loc[]函數(shù),我們可以訪問一個列并使用條件更改其值。
語法: df.loc[ df[“column_name”] == “some_value”, “column_name”] = “value”
注意:您也可以使用其他運算符來構(gòu)造條件以更改數(shù)值。
例子:在此示例中,代碼導(dǎo)入Pandas和NumPy庫,從保存學(xué)生數(shù)據(jù)的字典(‘Student’)構(gòu)建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數(shù)組。它為我們提供了一個非常有用的方法,where()可以訪問帶有條件的特定行或列。我們還可以使用此函數(shù)更改列的特定值。
語法: df[“column_name”] = np.where(df[“column_name”]==”some_value”, value_if_true, value_if_false)
例子:在此示例中,代碼導(dǎo)入Pandas和NumPy庫,從包含學(xué)生數(shù)據(jù)的名為“student”的字典中構(gòu)建名為“df”的DataFrame,并使用NumPy np.where函數(shù)將“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函數(shù)用于將任何行或列的值替換為條件。
語法: df[‘column_name’].mask( df[‘column_name’] == ‘some_value’, value , inplace=True )
例子:在此示例中,代碼導(dǎo)入Pandas和NumPy庫,從包含學(xué)生數(shù)據(jù)的名為“student”的字典中構(gòu)建名為“df”的DataFrame,然后使用Pandas mask函數(shù)將“gender”列中的值“female”替換為0,然后打印修改后的DataFrame。它還包括一行注釋,顯示如何有條件地將“math score”列中的值替換為“good”(對于大于或等于60的分?jǐn)?shù))。
# 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函數(shù)
在這個例子中,我們使用了lamda和apply()函數(shù)來根據(jù)條件替換列中的值。
# 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
到此這篇關(guān)于Pandas根據(jù)條件實現(xiàn)替換列中的值的文章就介紹到這了,更多相關(guān)Pandas替換列值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python+OpenCV圖片局部區(qū)域像素值處理改進版詳解
這篇文章主要為大家詳細(xì)介紹了Python+OpenCV圖片局部區(qū)域像素值處理的改進版,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-01-01
Python RabbitMQ消息隊列實現(xiàn)rpc
這篇文章主要介紹了python 之rabbitmq實現(xiàn)rpc,主要實現(xiàn)客戶端通過發(fā)送命令來調(diào)用服務(wù)端的某些服務(wù),服務(wù)端把結(jié)果再返回給客戶端,感興趣的小伙伴們可以參考一下2018-05-05
Django Admin實現(xiàn)三級聯(lián)動的示例代碼(省市區(qū))
多級菜單在很多上面都有應(yīng)用,這篇文章主要介紹了Django Admin實現(xiàn)三級聯(lián)動(省市區(qū)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06
python批量轉(zhuǎn)換word文檔為pdf文件的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何使用python編寫一個批量轉(zhuǎn)換word文檔為pdf文件的工具,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下2025-12-12
pip?install?jupyterlab失敗的原因問題及探索
在學(xué)習(xí)Yolo模型時,嘗試安裝JupyterLab但遇到錯誤,錯誤提示缺少Rust和Cargo編譯環(huán)境,因為pywinpty包需要它們來編譯,由于在conda環(huán)境下操作,Rust和Cargo已經(jīng)安裝,問題是pywinpty包丟失,安裝pywinpty包后,再次執(zhí)行pip?install?jupyterlab即可正常下載2025-02-02

