alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[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!

 
 

posted on   McDelfino  阅读(9)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2018-09-19 【334】Python Object-Oriented Programming
点击右上角即可分享
微信分享提示