[1064] Change values in a DataFrame based on different values
To change values in a DataFrame based on different values, you can use several methods in Pandas. Here are a few common approaches:
Using loc
for Conditional Replacement
You can use the loc
method to replace values based on a condition:
import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'Category': ['A', 'B', 'C', 'A', 'B'], 'Value': [10, 20, 30, 40, 50] }) # Replace values based on condition df.loc[df['Category'] == 'A', 'Value'] = 100 print(df)
Using replace
Method
The replace
method allows you to specify a dictionary for replacing values:
import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'Category': ['A', 'B', 'C', 'A', 'B'], 'Value': [10, 20, 30, 40, 50] }) # Replace values using a dictionary df['Category'] = df['Category'].replace({'A': 'X', 'B': 'Y'}) print(df)
Using np.where
for Conditional Replacement
You can also use NumPy’s where
function for more complex conditions:
import pandas as pd import numpy as np # Sample DataFrame df = pd.DataFrame({ 'Category': ['A', 'B', 'C', 'A', 'B'], 'Value': [10, 20, 30, 40, 50] }) # Replace values using np.where df['Value'] = np.where(df['Category'] == 'A', 100, df['Value']) print(df)
Using apply
with a Lambda Function
For more complex logic, you can use the apply
method with a lambda function:
import pandas as pd # Sample DataFrame df = pd.DataFrame({ 'Category': ['A', 'B', 'C', 'A', 'B'], 'Value': [10, 20, 30, 40, 50] }) # Replace values using apply and lambda df['Value'] = df.apply(lambda row: 100 if row['Category'] == 'A' else row['Value'], axis=1) print(df)
These methods should help you replace values in a DataFrame based on different conditions. If you have a specific scenario or need further assistance, feel free to ask!
分类:
Python Study
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2018-09-19 【334】Python Object-Oriented Programming