python - Pandas Dataframe 列的条件计算

标签 python pandas if-statement

我有一个 pandas 数据框,其内容为

Category  Sales  
A           10
B           20

我想有条件地创建新列目标

我希望我的目标 df 看起来像

Category  Sales  Target 
A           10    5
B           20   10

我使用了下面的代码,它抛出了一个错误

if(df['Category']=='A'):
    df['Target']=df['Sales']-5
else:
    df['Target']=df['Sales']-10

最佳答案

使用矢量化numpy.where :

df['Target']= np.where(df['Category']=='A', df['Sales'] - 5, df['Sales'] - 10)
print (df)
  Category  Sales  Target
0        A     10       5
1        B     20      10

关于python - Pandas Dataframe 列的条件计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50483428/

相关文章:

java - 如果满足多个条件,如何使用 If 语句计算数字?

python - 我做的python计算器出错了

python - 从数据框格式的文本列中提取单词

python - pandas 通过时间索引打破数据帧的快速方法

python - Matplotlib:根据标准识别条形图中的条形

c++ - if 语句不能正常工作?

Python Selenium - 如何终止未成功生成的 Chromedriver?

Python 模拟库 : Is there any way to get corresponding return values from magic mock calls?

python - 为什么 x 轴使用日期和 matplotlib 上 x 轴使用数字列表之间的绘图显示不同?

JavaScript If 语句和组合框功能