在 Python 中使用 if else case 来获得派生列
Using if else case in Python to have a derived column
我的代码中有一个查询,我在其中尝试使用 if else case 来导出数据框中的值,
import pandas as pd
import numpy as np
c=15
s={'yr':[2014,2014,2014,2014],'value':[10,20,20,50]}
p=pd.DataFrame(data=s)
if (p['value'])>= c:
p['qty']=c-p['value']
else:
p['value']
我在上面的代码中遇到错误-
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
基本上这应该是我的预期输出-
yr value qty
0 2014 10 10
1 2014 20 5
2 2014 20 5
3 2014 50 35
我该如何解决这个错误?
if
需要一个布尔值 (True/False) 但 (p['value'])>= c
是一个系列,所以你会得到那个错误。获得所需输出的一种方法是使用 mask
:
p['qty'] = p['value'].mask(lambda x: x>=c, p['value']-c)
另一种选择是使用 numpy.where
:
import numpy as np
p['qty'] = np.where(p['value']>=c, p['value']-c, p['value'])
输出:
yr value qty
0 2014 10 10
1 2014 20 5
2 2014 20 5
3 2014 50 35
您可以使用 loc 语句 select 某些行:
# initialize the qty column
df['qty'] = df['value']
# adjust qty where qty is larger than c
df.loc[df['qty'] > c, 'qty'] -= c
您正在尝试对通常需要迭代或应用函数的列进行操作element-wise
p['qty'] = p['value'].apply(lambda x: c - x if x >= c else x)
使用 np.where
的解决方案,假设您的预期计算是 p['value']-c
而不是 c-p['value']
:
p['qty'] = np.where(p['value'] >= c, p['value']-c, p['value'])
结果:
yr value qty
0 2014 10 10
1 2014 20 5
2 2014 20 5
3 2014 50 35
我的代码中有一个查询,我在其中尝试使用 if else case 来导出数据框中的值,
import pandas as pd
import numpy as np
c=15
s={'yr':[2014,2014,2014,2014],'value':[10,20,20,50]}
p=pd.DataFrame(data=s)
if (p['value'])>= c:
p['qty']=c-p['value']
else:
p['value']
我在上面的代码中遇到错误-
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
基本上这应该是我的预期输出-
yr value qty
0 2014 10 10
1 2014 20 5
2 2014 20 5
3 2014 50 35
我该如何解决这个错误?
if
需要一个布尔值 (True/False) 但 (p['value'])>= c
是一个系列,所以你会得到那个错误。获得所需输出的一种方法是使用 mask
:
p['qty'] = p['value'].mask(lambda x: x>=c, p['value']-c)
另一种选择是使用 numpy.where
:
import numpy as np
p['qty'] = np.where(p['value']>=c, p['value']-c, p['value'])
输出:
yr value qty
0 2014 10 10
1 2014 20 5
2 2014 20 5
3 2014 50 35
您可以使用 loc 语句 select 某些行:
# initialize the qty column
df['qty'] = df['value']
# adjust qty where qty is larger than c
df.loc[df['qty'] > c, 'qty'] -= c
您正在尝试对通常需要迭代或应用函数的列进行操作element-wise
p['qty'] = p['value'].apply(lambda x: c - x if x >= c else x)
使用 np.where
的解决方案,假设您的预期计算是 p['value']-c
而不是 c-p['value']
:
p['qty'] = np.where(p['value'] >= c, p['value']-c, p['value'])
结果:
yr value qty
0 2014 10 10
1 2014 20 5
2 2014 20 5
3 2014 50 35